什麼是RPCgit
RPC是Remote Procedure Call簡稱,翻譯過來是遠程過程調用。它是一個進程間的通信技術,基於Client-Server模式,讓程序像調用本地方法同樣使用,而無需去關係它細節如何實現。github
上面是個人理解,怕理解有錯或者表達不許確,下面引用維基百科服務器
維基百科 a remote procedure call (RPC) is when a computer program causes a procedure (subroutine) to execute in a different address space (commonly on another computer on a shared network), which is coded as if it were a normal (local) procedure call, without the programmer explicitly coding the details for the remote interaction網絡
網上找到一個圖,比較形象描述RPC調用過程數據結構
何時須要RPCapp
RPC是解決進程間通信(能夠是同一個服務器,也能夠是不一樣服務器的進程間,可是一般是內網的不一樣服務器之間進程通信)。 框架
解決進程間通訊,Web Api也是能夠解決,爲何還須要RPC?我認爲能夠從下面幾點ide
1. Web Api是基於HTTP,RPC能夠是HTTP,也能夠是TCP,甚至基於Socket,RPC框架一般都是隱藏通信細節,讓咱們無感知使用微服務
2. Web Api 一般基於JSON格式,XML格式,這種格式易讀性強,可是隨之帶來就是傳輸過程須要把數據的元數據也帶進去傳輸
3. Web Api更多應用場景是提供方定義好接口,由客戶端按需調用,RPC一般須要調用方和提供方溝通一塊兒定義接口
因此PRC更可能是使用如下場景
gRPC使用
gRPC是Google開源的高性能RPC框架,有如下幾個特色
協定優先 API 開發,默認使用protobuf,容許與語言無關的實現。(這裏涉及兩點,1.面向接口開發,依賴抽象而不是具體,2. 能夠不一樣語言實現協做)
使用 Protobuf 二進制序列化減小對網絡的使用。(減小網絡傳輸)
可用於多種語言的工具,以生成強類型服務器和客戶端。
支持客戶端、服務器和雙向流式處理調用。
下面開始介紹如何在Net Core上使用gRPC
1、安裝dotnet-gRPC工具(用於引用protobuf文件,生成客戶端/服務端代碼)
dotnet tool install dotnet-grpc -g
2、新建一個protobuf文件
syntax = "proto3"; option csharp_namespace = "gRPC.Services"; package sms; // The greeting service definition. service SmsSender { // Sends a greeting rpc SendSms (SmsRequest) returns (SmsResponse); } // The request message containing the user's name. message SmsRequest { string tel = 1; string content = 2; } // The response message containing the greetings. message SmsResponse { int32 code = 1; string message = 2; }
3、新建一個服務端
1. 新建一個gRPC工程
dotnet new grpc -n gRPC.Services
2. 引入步驟二生成的protobuf文件(可使用通配符引入多個protobuf文件)
dotnet-grpc add-file ..\gRPC.Protos\*.proto -s Serve
3. 新建服務類
public class SmsService : SmsSender.SmsSenderBase { private readonly ILogger<SmsService> _logger; public SmsService(ILogger<SmsService> logger) { _logger = logger; } public override Task<SmsResponse> SendSms(SmsRequest request, ServerCallContext context) { return Task.FromResult(new SmsResponse { Code = 1, Message = "發送成功" }); } }
4. 配置grpc服務類終結點
app.UseEndpoints(endpoints => { endpoints.MapGrpcService<SmsService>(); });
4、新建客戶端
1. 新建控制檯程序
dotnet new console -n gRPC.Client
2. 添加包(Google.Protobuf)
dotnet add package Google.Protobuf
3. 引入步驟二生成的protobuf文件(可使用通配符引入多個protobuf文件),注意:這裏須要生成是客戶端代碼,固然也能夠用Both參數生成
dotnet-grpc add-file ..\gRPC.Protos\*.proto -s Client
5、運行
1. 運行服務端
2. 啓動客戶端
客戶端輸出下面信息
{"Code":1,"Message":"\u53D1\u9001\u6210\u529F"}
6、小結
gRPC的生命週期
Client(發送請求) -> Client stub(壓縮/解壓) -> Client RPC Transfer(發送/接收) -> Server RPC Transfer(接收/發送) -> Server stub(解壓/壓縮) -> Server (處理響應)
gPRC幫咱們隱藏中間的環節,只剩下兩頭的代碼(俗稱業務邏輯代碼)
protobuf它是一種可序列化的數據結構,但它更重要是定義接口,讓服務端和客戶端能分離出來
轉發請標明出處:https://www.cnblogs.com/WilsonPan/p/12000796.html
示例代碼:https://github.com/WilsonPan/AspNetCoreExamples/tree/master/gRPC