上一篇博客把grpc的概念说了个大概,介绍了proto的数据类型,基本语法,也写了个小demo,是否是没那么难?git
今天要从理论到实际,写两个微服务,并利用grpc完成二者之间的通讯。只是做为demo写的话会十分简单,毕竟理解为主。app
首先要拿出以前写好的proto文件,而后修改两个属性:异步
Build Action => Protobuf compiler
gRpc Stub Classes => Server only
如图:async
固然也能够在项目文件里看到它:ide
而后从新生成项目 ,会自动根据proto文件生成server端的文件。微服务
通过刚才,已经生成了对应的服务,咱们能够直接在代码里调用。ui
这是以前写好的proto:this
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这个类,咱们来继承一下:spa
注意看命名空间,这是刚才项目生成之后根据proto生成的。code
如今来重写一下里面的方法(下图是生成,也能够手动写):
根据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