.Net Core微服务rpc框架GRPC通信实际运用

Halima ·
更新时间:2024-09-20
· 1448 次阅读

上一篇博客把grpc的概念说了个大概,介绍了proto的数据类型,基本语法,也写了个小demo,是不是没那么难?

今天要从理论到实际,写两个微服务,并利用grpc完成两者之间的通信。只是作为demo写的话会十分简单,毕竟理解为主。

服务端

首先要拿出之前写好的proto文件,然后修改两个属性:

Build Action => Protobuf compiler gRpc Stub Classes => Server only

如图:

当然也可以在项目文件里看到它:

然后重新生成项目 ,会自动根据proto文件生成server端的文件。

引用

经过刚才,已经生成了对应的服务,我们可以直接在代码里调用。

这是之前写好的proto:

syntax = "proto3"; option csharp_namespace = "gRPCApiDemo.Protos"; package Demo; service MyMath{ rpc MathAdd (AddRequest) returns (AddRespones) {} } message AddRequest{ int32 a=1; int32 b=2; } message AddRespones{ int32 a=1; }

生成以后,会有一个MyMath.MyMathBase这个类,我们来继承一下:

注意看命名空间,这是刚才项目生成以后根据proto生成的。

现在来重写一下里面的方法(下图是生成,也可以手动写):

根据proto文件可知:

AddRequest包含两个int参数:A、B

AddRespones包含一个名为A的int参数

那我们把AB相加然后返回:

using Grpc.Core; using gRPCApiDemo.Protos; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace gRPCApiDemo.Grpc { public class GrpcServiceMath : MyMath.MyMathBase { public override Task<AddRespones> MathAdd(AddRequest request, ServerCallContext context) { var respones = new AddRespones { A = request.A + request.B }; return Task.FromResult(respones); } } }

再然后进入StartUp设置一下:

 app.UseHttpsRedirection(); app.UseEndpoints(endpoints => { endpoints.MapGrpcService<MathServices>(); });

服务端到这里就写完了。

如果写了更多service,那就需要在这里声明更多的实现类;而且https是必须的。

客户端

我准备了一个空白项目。接下来你可以把之前服务端的proto文件拷贝过来,或者选择重新写一份,然后修改属性以后生成一下项目:

其实还有一个选项是Client and Server,一次生成客户端和服务端。

接下来注入灵魂:

services.AddGrpcClient<MyMath.MyMathClient>(o => o.Address = new Uri("https://localhost:5001"));

MyMath是proto里声明的服务,MyMathClient是刚才生成的,里面的Uri是服务端所在的域名。

因为gRpc是基于http/2,而想要以http/2访问有个比较麻烦的证书要搞,如果不想搞证书可以接着添加这一行:

AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);

当然,别忘了下面https的设置。

再接着我们新建一个controller,直接调用方法:

public class IndexController : Controller { private readonly MyMath.MyMathClient _client; public IndexController(MyMath.MyMathClient client) { this._client = client; } public async Task<int> Add(int a, int b) { var respones = await _client.MathAddAsync(new AddRequest() { A = a, B = b }); return respones.A; } }

MyMathClient就和MyMathBase一样,也是自动生成的。而且现在这个版本会自动生成rpc调用的异步版本,就像代码里的MathAddAsync。

我们跑一下看看:

完美。

源码地址

最后小小的提醒一下,server和client端必须要有https,不然的话:

希望对初入微服务的同学有所帮助。

最后附上源码:

https://gitee.com/muchengqingxin/GrpcServerDemo.git

https://gitee.com/muchengqingxin/GrpcClientDemo.git

到此这篇关于.Net Core微服务rpc框架GRPC通信实际运用的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持软件开发网。



net .NET grpc rpc core

需要 登录 后方可回复, 如果你还没有账号请 注册新账号