天天看點

ASP.NET Core 中建立 gRPC 用戶端和伺服器

建立項目:GRPC.Server.Demo

ASP.NET Core 中建立 gRPC 用戶端和伺服器

添加項目檔案夾:Protos  裡面的檔案添加 ProtosFile檔案夾裡的檔案

ASP.NET Core 中建立 gRPC 用戶端和伺服器

解決方案:

ASP.NET Core 中建立 gRPC 用戶端和伺服器

GrpcGreeter 項目檔案 :

  • greet.proto – Protos/greet.proto 檔案定義 

    Greeter

     gRPC,且用于生成 gRPC 伺服器資産 。 有關詳細資訊,請參閱 gRPC 介紹。
  • Services 檔案夾:包含 

    Greeter

     服務的實作。
  • appSettings.json – 包含配置資料,如 Kestrel 使用的協定。 有關詳細資訊,請參閱 ASP.NET Core 中的配置。
  • Program.cs – 包含 gRPC 服務的入口點。 有關詳細資訊,請參閱 .NET 通用主機。
  • Startup.cs – 包含配置應用行為的代碼。 有關詳細資訊,請參閱應用啟動。

GRPC.Server.Demo.csproj 添加一段如下:

<ItemGroup>
    <Protobuf Include="**/*.proto" OutputDir="auto-generated" CompileOutputs="false" GrpcServices="Server" />
  </ItemGroup>
           

GreeterService.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Grpc.Core;
using GRPC.Server.Demo;
using Microsoft.Extensions.Logging;

namespace GRPC.Server.Demo.Services
{
    public class GreeterService : Greeter.GreeterBase
    {
        private readonly ILogger<GreeterService> _logger;
        public GreeterService(ILogger<GreeterService> logger)
        {
            _logger = logger;
        }

        public override Task<HelloReply> SayHello(HelloRequest request, ServerCallContext context)
        {
            return Task.FromResult(new HelloReply
            {
                Message = "Hello " + request.Name
            });
        }
    }
}
           

建立項目:GRPC.Client.Demo

方案一:

gRPC 用戶端項目需要以下包:

  • Grpc.Net.Client,其中包含 .NET Core 用戶端。
  • Google.Protobuf 包含适用于 C# 的 Protobuf 消息。
  • Grpc.Tools 包含适用于 Protobuf 檔案的 C# 工具支援。 運作時不需要工具包,是以依賴項标記為 

    PrivateAssets="All"

添加項目檔案夾:Protos 同上 

GRPC.Client.Demo.csproj 添加一段如下:

<ItemGroup>
    <Protobuf Include="**/*.proto" OutputDir="auto-generated" CompileOutputs="false" GrpcServices="Client" />
  </ItemGroup>
           

方案二:

ASP.NET Core 中建立 gRPC 用戶端和伺服器

Program.cs

using Grpc.Net.Client;
using GRPC.Server.Demo;
using System;
using System.Threading.Tasks;

namespace GRPC.Client.Demo
{
    class Program
    {
        static async Task Main(string[] args)
        {
            // The port number(5001) must match the port of the gRPC server.
            var channel = GrpcChannel.ForAddress("https://localhost:5001");
            var client = new Greeter.GreeterClient(channel);
            var reply = await client.SayHelloAsync(
                              new HelloRequest { Name = "GreeterClient" });
            Console.WriteLine("Greeting: " + reply.Message);
            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();

            Console.WriteLine("Hello World!");
        }
    }
}
           

 運作效果:

ASP.NET Core 中建立 gRPC 用戶端和伺服器

參考文獻:

https://github.com/grpc

https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/grpc/grpc-start?view=aspnetcore-3.0&tabs=visual-studio

https://docs.microsoft.com/zh-cn/aspnet/core/grpc/index?view=aspnetcore-3.0

繼續閱讀