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