grpc是干嘛的?
grpc的定义网上都有非常官方的说明,这里从它的用法角度描述这个概念。
有了 gRPC, 我们可以一次性的在一个 .proto 文件中定义服务并使用任何支持它的语言去实现客户端和服务器,反过来,它们可以在各种环境中,从Google的服务器到你自己的平板电脑—— gRPC 帮你解决了不同语言间通信的复杂性以及环境的不同。使用 protocol buffers 还能获得其他好处,包括高效的序列号,简单的 IDL 以及容易进行的接口更新。{来源:grpc官方文档}
grpc实例用法
grpc使用主要有如下步骤
- 通过Protocol Buffer来定义接口和数据类型
- 通过Protocol Buffer编译器编译proto文件为对应平台的代码文件
- 编写gRPC server端代码
- 编写gRPC client端代码
建立proto并且编译
syntax = "proto3"; //指定语法proto2或proto3 本文采用proto3
//package gRpcDemo; //指定命名空间
option csharp_namespace = "gRpcDemo";
//定义rpc服务
service gRpcQueryService
{
rpc Search(QureyCond) returns (QueryResult);
}
//定义查询条件消息体
message QureyCond
{
int32 id=1; //通过id查询
}
//定义查询结果实体对象
message QueryResult
{
int32 id=1;
string name=2;
int32 age=3;
}
这里还需要再nuget中安装相关的grpc包 ,包括如下所示
然后使用命令对其进行编译
-I:设定源路径
--csharp_out::第一个参数设定编译文件的路径,第二个参数设定需要编译的proto文件;如果使用其它语言请使用对应语言的option
--grpc_out:设定输出路径
--plugin:设定编译需要的插件
使用的编译工具再刚刚装好的Grpc.Tools包下(grpc.tools\2.25.0-pre1\tools\windows_x64 下找到protoc.exe和grpc_csharp_plugin.exe ,然后一般这些安装好的依赖包都在C盘用户目录下的.nuget文件夹下),随后编辑命令
server端服务
using Grpc.Core;
using gRpcDemo;
using System;
using System.Threading.Tasks;
namespace gRpcService
{
class Program
{
const int Port = 8050;
static void Main(string[] args)
{
//开启服务器端口,并且将远程调用绑定服务接口
Server server = new Server
{
Services = { gRpcQueryService.BindService(new GRPCImpl()) },
Ports = { new ServerPort("localhost", Port, ServerCredentials.Insecure) }
};
server.Start();
Console.WriteLine("gRpc server listening on port" + Port);
Console.ReadKey();
server.ShutdownAsync().Wait();
}
}
class GRPCImpl : gRpcQueryService.gRpcQueryServiceBase
{
public override Task<QueryResult> Search(QureyCond request,ServerCallContext context)
{
return Task.FromResult(Search(request));
}
private QueryResult Search(QureyCond cond)
{
QueryResult result = new QueryResult();
result.Id = cond.Id;
result.Name = "zhangsan";
result.Age = 15;
return result;
}
}
}
client端
using System;
using Grpc.Core;
using gRpcDemo;
namespace gRpcClient
{
class Program
{
static void Main(string[] args)
{
Channel channel = new Channel("localhost:8050", ChannelCredentials.Insecure);
var client = new gRpcQueryService.gRpcQueryServiceClient(channel);
var result = client.Search(new QureyCond { Id = 3 });
Console.WriteLine("结果:id={0} name={1} age={2}", result.Id, result.Name, result.Age);
channel.ShutdownAsync().Wait();
Console.WriteLine("任意键退出...");
Console.ReadKey();
}
}
}
最终实现
参考
https://www.cnblogs.com/stulzq/p/11590088.html
https://blog.csdn.net/uiuan00/article/details/102831031
https://blog.csdn.net/weixin_41563161/article/details/106347789