序
上一篇部落格把grpc的概念說了個大概,介紹了proto的資料類型,基本文法,也寫了個小demo,是不是沒那麼難?
今天要從理論到實際,寫兩個微服務,并利用grpc完成兩者之間的通信。隻是作為demo寫的話會十分簡單,畢竟了解為主。
服務端
首先要拿出之前寫好的proto檔案,然後修改兩個屬性:
Build Action => Protobuf compiler
gRpc Stub Classes => Server only
如圖:
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyZuBnLwMzMyQjM5cTMtYDO0kjM2MTMxMTM3ADMyAjMtIjM1UzN38CX3ADMyAjMvwlMyUTN3czLcd2bsJ2Lc12bj5ycn9Gbi52YuAjMwIzZtl2Lc9CX6MHc0RHaiojIsJye.png)
當然也可以在項目檔案裡看到它:
然後重新生成項目 ,會自動根據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
聲明:未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接配接,否則視為侵權。
本文原創發表于部落格園,作者為暮城傾心。歡迎轉載。Donation(掃碼支援作者)↓
-
.Net Core微服務——GRPC通信(下) - 微信
-
.Net Core微服務——GRPC通信(下) - 支付寶