序
上一篇博客把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