gRPC-浅试

最近接到业务需求,对接外包算法的http接口,了解了gRPC的使用,这里以一个简单的例子说明。

1 新建程序

新建gRPCClientgRPCServer

2 添加引用

打开NuGet,安装GrpcGoogle.ProtobufGrpc.Tools

 

3 定义服务

 定义LogService.proto文件,如下代码:我这里是将服务放在gRPCServer下,也可以放在其他项目下

 1 //指定语法proto2或proto3 本文采用proto3
 2 syntax = "proto3";
 3 
 4 //指定命名空间
 5 option csharp_namespace = "gRPCServer";
 6 
 7 //定义rpc服务
 8 service gRpcQueryService
 9 {
10     rpc Search(QureyCond) returns (QueryResult);
11 }
12 
13 //定义查询条件消息体
14 message QureyCond
15 {
16     int32 id=1;        //通过id查询        
17 }
18 
19 //定义查询结果实体对象
20 message QueryResult
21 {
22     int32 id=1;        
23     string name=2;        
24     int32 age=3;    
25 }
View Code

 4 生成代码

打开CMD,在项目的packages文件夹可找到Grpc.Tools 通过cd /d 命令转到packages上一级目录

指定protoc.exe路径:packages\Grpc.Tools.2.50.0\tools\windows_x64\protoc.exe 

指定proto文件搜索目录:-IgRPCServer  

C#代码生成路径:--csharp_out gRPCServer

指定proto文件:gRPCServer\LogService.proto

grpc文件生成路径:--grpc_out gRPCServer

指定grpc_csharp_plugin.exe路径:--plugin=protoc-gen-grpc=packages\Grpc.Tools.2.50.0\tools\windows_x64\grpc_csharp_plugin.exe

输入命令运行成功得到两个cs文件,将文件添加到项目中。

 5 服务端

定义监听服务

 1  const int Port = 8050;
 2         public static void Main(string[] args)
 3         {
 4             Server server = new Server
 5             {
 6                 Services = { gRpcQueryService.BindService(new GRPCImpl()) },
 7                 Ports = { new ServerPort("localhost", Port, ServerCredentials.Insecure) }
 8             };
 9 
10             server.Start();
11             Console.WriteLine("gRPC server listening on port " + Port);
12             Console.WriteLine("任意键退出...");
13             Console.ReadKey();
14 
15             server.ShutdownAsync().Wait();
16         }
View Code

具体服务内容

 1 class GRPCImpl : gRpcQueryService.gRpcQueryServiceBase
 2     {
 3         public override Task<QueryResult> Search(QureyCond request, ServerCallContext context)
 4         {
 5             return Task.FromResult(Search(request));
 6 
 7         }
 8 
 9         private QueryResult Search(QureyCond cond)
10         {
11             //自定义逻辑
12             QueryResult result = new QueryResult();
13             result.Id = cond.Id;
14             result.Name = "";
15             result.Age = 23;
16             return result;
17         }
18     }
View Code

6 客户端

调用方法

1  Channel channel = new Channel("127.0.0.1:8050", ChannelCredentials.Insecure);
2             var client = new gRpcQueryService.gRpcQueryServiceClient(channel);
3             var result = client.Search(new QureyCond { Id = 2 });
4             Console.WriteLine("结果:id={0} name={1} age={2}", result.Id, result.Name, result.Age);
5             channel.ShutdownAsync().Wait();
6             Console.WriteLine("任意键退出...");
7             Console.ReadKey();
View Code

7 调用效果

先打开gRPCServer

再打开gRPCClient

 

 

 

 

 

 

 

 

 

posted @ 2022-10-29 10:22  htiu  阅读(65)  评论(0编辑  收藏  举报