.NET使用gRPC入门教程

   gRPC是一个高性能、通用的开源RPC框架,其由Google主要面向移动应用开发并基于HTTP/2协议标准而设计,基于ProtoBuf(Protocol Buffers)序列化协议开发,且支持众多开发语言,能够基于语言自动生成客户端和服务端功能库。

1.新建工程GrpcClient、GrpcServer和GrpcLibrary

   添加 - 新建项目 - 控制台应用 GrpcClient、GrpcServer。

   添加 - 新建项目 - 类库 GrpcLibrary。 工程中的三个项目情况如下:

   

2.安装程序包Grpc

   三个项目GrpcClient、GrpcServer、GrpcLibrary均安装程序包Grpc。

   属性- 管理NuGet程序包 - 安装Grpc

3.安装程序包Google.Protobuf 

三个项目GrpcClient、GrpcServer、GrpcLibrary均安装程序包Google.Protobuf 。

属性- 管理NuGet程序包 - 安装Google.Protobuf 

4.安装程序包Grpc.Tools

 类库GrpcLibrary安装程序包Grpc.Tools。

 属性- 管理NuGet程序包 - 安装Grpc.Tools。

5.自定义服务

  在项目GrpcLibrary里添加HelloWorld.proto用以生成代码。

syntax = "proto3";
package GrpcLibrary;
service GrpcService {
  rpc SayHello (HelloRequest) returns (HelloReply) {}
}

message HelloRequest {
  string name = 1;
}

message HelloReply {
  string message = 1;
}

  执行命令

packages\Grpc.Tools.1.17.0\tools\windows_x64\protoc.exe -IGrpcLibrary --csharp_out GrpcLibrary  GrpcLibrary\HelloWorld.proto --grpc_out GrpcLibrary --plugin=protoc-gen-grpc=packages\Grpc.Tools.1.17.0\tools\windows_x64\grpc_csharp_plugin.exe

命令执行成功后,GrpcLibrary目录下会生成HelloWorld.cs和HelloWorldGrpc.cs。

将HelloWorld.cs和HelloWorldGrpc.cs都添加到项目GrpcLibrary中。

最后GrpcClient、GrpcServer分别引用类库GrpcLibrary。

6.服务端

using Grpc.Core;
using GrpcLibrary;
using System;
using System.Threading.Tasks;

namespace GrpcServer
{
    class GrpcImpl : GrpcService.GrpcServiceBase
    {
        // 实现SayHello方法
        public override Task<HelloReply> SayHello(HelloRequest request, ServerCallContext context)
        {
            return Task.FromResult(new HelloReply { Message = "Hello " + request.Name });
        }
    }
    class Program
    {
        const int Port = 9007;

        public static void Main(string[] args)
        {
            Server server = new Server
            {
                Services = { GrpcService.BindService(new GrpcImpl()) },
                Ports = { new ServerPort("localhost", Port, ServerCredentials.Insecure) }
            };
            server.Start();

            Console.WriteLine("GrpcService server listening on port " + Port);
            Console.WriteLine("任意键退出...");
            Console.ReadKey();

            server.ShutdownAsync().Wait();
        }
    }
}

7.客户端

using Grpc.Core;
using GrpcLibrary;
using System;

namespace GrpcClient
{
    class Program
    {
        static void Main(string[] args)
        {
            Channel channel = new Channel("127.0.0.1:9007", ChannelCredentials.Insecure);

            var client = new GrpcService.GrpcServiceClient(channel);
            var reply = client.SayHello(new HelloRequest { Name = "April" });
            Console.WriteLine("来自" + reply.Message);

            channel.ShutdownAsync().Wait();
            Console.WriteLine("任意键退出...");
            Console.ReadKey();
        }
    }
}

8.测试

先启动服务的,再启动客户端。