C#中使用gRPC


C#中使用gRPC

我的這幾篇文章都是使用gRPC的example,不是直接編譯example,而是新建一個項目,從添加依賴,編譯example代碼,執行example。這樣做可以為我們創建自己的項目提供借鑒。如果對gRPC構建應用很熟悉,可以無視本系列文章。

目錄

一、概述

二、編譯gRPC

三、C#中使用gRPC

四、C++中使用gRPC

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

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

protocol buffer 3.0版本,在NuGet插件界面選擇Include Prerelease,查找google protocol buffer。
如果不選擇include rerelease,查找到的protocol buffer是2.4的,無法編譯通過gRPC的example。

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 greetings message HelloReply { string message = 1; }

3. 生成proto訪問類

定義proto文件后,通過protocol buffer3.0提供的protoc.exe工具生成訪問類。這里使用gRPC定義的protoc的C#插件grpc_csharp_plugin.exe,而不是使用protoGen.exe。
將以下幾個文件放在同一個文件夾中:

grpc_csharp_plugin.exe helloworld.proto protoc.exe

創建一個bat文件,編寫如下命令行:

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

執行bat文件,得到proto的訪問類:

helloworld.cs helloworldGrpc.cs

4. 創建C#項目

將兩個訪問類文件添加到C#項目中,將gRPC的C# example拷貝到Program.cs中,編譯通過。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM