GRPC是什么?
GRPC是一個開源RPC框架,於2015年3月開源,其由Google主要面向移動應用開發並基於HTTP/2協議標准而設計,基於Protobuf 3.0(Protocol Buffers)序列化協議,主流語言都支持 主要是支持C#
使用場景?
實現客戶端調用服務端方法並取返回值 GRPC可以實現跨語言的訪問
下面跟着官網文檔開始干
1)先了解下protobuf?
Protocol Buffers是Google開源的一個語言無關、平台無關的通信協議,其小巧、高效和友好的兼容性設計,使其被廣泛使用。
2)VS2015下新建項目
分別建立兩個項目跟一個類庫 分別代表着服務端 客戶端 基礎類庫
3)引用dll
需要使用NuGet下載安裝 *並引用* Google.Protobuf Grpc.Core Grpc.Tools 網站項目需要共同Publicl類庫
4)定義服務
在Public類庫新建文件夾命名為protos用來存放.proto文件,在文件夾下新建GetUser.proto文件 內容如下
syntax = "proto3"; option java_multiple_files = true; option java_package = "io.grpc.examples.Public"; option java_outer_classname = "GetUserProto"; option objc_class_prefix = "HLW"; package Public; //定義的服務 service GetUserList { rpc GetList(pharm) returns (Userlist) {} } //服務的參數 message pharm { string name = 1; } //返回參數 message Userlist { user userinfo=1; int32 no=2; } message user{ string name=1; string detail=2; }
5)生成代碼
生成代碼需要使用官網提供的grpc_csharp_plugin.exe跟protoc.exe ,工具位置在 _你的項目>> packages>>Grpc.Tools.1.14.1>>tools>>windows_x64
(也可在官網demo中找到 https://github.com/grpc/grpc)
把兩個exe跟剛建好的GetUser.proto放入同一個文件夾下 地址欄運行cmd
執行命令如下:protoc.exe -I=. --csharp_out=. --grpc_out=. --plugin=protoc-gen-grpc=grpc_csharp_plugin.exe GetUser.proto
6)把cs文件剪切到Public類庫下 ,目錄結構如下
7)建立服務端
服務端重寫定義的服務GetUserList
GrpcDemoWebServer項目->新建GetUserI.cs文件 代碼如下:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Public; using Grpc.Core; using System.Threading.Tasks; namespace GrpcDemoWeb.Models { public class GetUserI:GetUserList.GetUserListBase { public override Task<Userlist> GetList(pharm request, ServerCallContext context) { var users = new user(); users.Name = "姓名"; users.Detail = "描述";
//以下注意 不能將null值賦值給Userinfo return Task.FromResult(new Userlist { Userinfo= users, No=1 }); } } }
在服務端Global.asax->Application_Start中啟動服務 代碼如下:
const int Port = 50051; Server server = new Server {
//重要,每次新建服務都需要在下方注冊,否則會出現錯誤 【Status(StatusCode=Unimplemented,Detail="")】 Services = { GetUserList.BindService(new GetUserI()) }, Ports = { new ServerPort("localhost", Port, ServerCredentials.Insecure) } }; server.Start(); //server.ShutdownAsync().Wait();
8)建立客戶端
GRpcDemoWebClient-》新建控制器index->代碼如下:
public ActionResult Index() { //鏈接對應的服務端 Channel channel = new Channel("127.0.0.1:50051", ChannelCredentials.Insecure); var result = new GetUserList.GetUserListClient(channel); //var client = new GetUser.GetUserClient(channel); //調用對應方法並傳遞參數 var reply = result.GetList(new pharm {Name="1"}); //var reply1 = client.GetFeature(new Point { Latitude = 111, Longitude = 222 }); //等待計划完成 channel.ShutdownAsync().Wait(); //返回頁面 return Content(reply.Userinfo.Name); }
9)IIS上部署兩個項目 按順序打開 1服務端 2打開客戶端下/index 展示內容為“”姓名“”表示成功
9)難點記錄:
還需要多加理解Protocolbuffers
rpc流式傳遞