首頁  >  文章  >  後端開發  >  C#中使用gRPC

C#中使用gRPC

黄舟
黄舟原創
2017-02-07 16:52:044454瀏覽

由於有NuGet,使得C#在配置專案時非常簡單。

1. 在NuGet中加入ProtocolBuffer和gRPC引用

protocol buffer 3.0版本,在NuGet外掛程式介面選擇Include Prerelease,尋找google protocol buffer。
如果不選擇include rerelease,查找到的protocol buffer是2.4的,無法編譯

2.定義proto

設計proto協議文件,包括服務協議和數據。 gRPC必須使用protocol buffer3.0版本,所以syntax設定為proto3。
Greeter是服務名稱
HelloRequest是請求資料
HelloReply是回覆資料

syntax = "proto3";option java_multiple_files = true;option java_package = "io.grpc.examples.helloworld";
option java_outer_classname = "HelloWorldProto";option objc_class_prefix = "HLW";

package helloworld;

// The greeting service definition.
service Greeter {
  // Sends a greeting
  rpc SayHello (HelloRequest) returns (HelloReply) {}
}

// The request message containing the user's name.message HelloRequest {  string name = 1;
}

// The response message containing the greetingsmessage HelloReply {  string message = 1;
}

3. 產生proto存取類別

定義proto檔案後,透過protocol buffer3.0提供的protoc.exe工具產生存取類別。這裡使用gRPC定義的protoc的C#外掛程式grpc_csharp_plugin.exe,而不是使用protoGen.exe。
將以下幾個文件放在同一個資料夾中:

grpc_csharp_plugin.exehelloworld.protoprotoc.exe

建立一個bat文件,編寫如下命令列:

protoc.exe -I=. --csharp_out=. --grpc_out=. --plugin=protoc-gen-grpc=grpc_csharp_plugin.exe helloworld.proto

執行bat文件,得到proto的存取類別:

helloworld.cshelloworldGrpc.cs

4. 建立C#專案將兩個存取類別檔案加入C#專案中,將gRPC的C# example拷貝到Program.cs中,編譯通過。

以上就是C#中使用gRPC的內容,更多相關內容請關注PHP中文網(www.php.cn)!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn