博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
如何编译C#版本的Protocol Buffers与gRPC服务端,客户端代码
阅读量:7007 次
发布时间:2019-06-27

本文共 1603 字,大约阅读时间需要 5 分钟。

定义Protocol Buffers

message.proto

syntax = "proto3";package Greet;// The request message containing the user's name.message HelloRequest {    string name = 1;}// The response message containing the greetings.message HelloReply {    string message = 1;}复制代码

greet.proto

syntax = "proto3";package Greet;option csharp_namespace = "Greet";import "message.proto";// The greeting service definition.service Greeter {  // Sends a greeting  rpc SayHello (HelloRequest) returns (HelloReply) {}}复制代码

csharp_namespace这个是针对C#独有的可选配置,如果namespace与package相同,可以不用写。

使用protoc手动编译

protoc.exe可以在以下地址下载:

如果使用nuget安装过Google.Protobuf.Tools,在这个目录也可以找到protoc.exe %UserProfile%.nuget\packages\Google.Protobuf.Tools\3.7.0\tools\windows_x64\protoc.exe

最简单的编译bat可以这样写:

protoc --csharp_out=./ greet.proto复制代码

--csharp_out是必选参数, 还有一个-I为可选参数,默认为当前目录,指定代码目录

如果需要同时编译服务端和客户端代码,需要grpc_csharp_plugin,可以在Grpc.Tools nuget包中找到: %UserProfile%.nuget\packages\Grpc.Tools\1.20.0\tools\windows_x64\grpc_csharp_plugin.exe

set PLUGIN=%UserProfile%\.nuget\packages\Grpc.Tools\1.20.0\tools\windows_x64\grpc_csharp_plugin.exeD:\Grpc\protoc-3.7.1-win64\bin\protoc.exe --csharp_out=./ greet.proto --grpc_out ./ --plugin=protoc-gen-grpc=%PLUGIN%复制代码

使用Visual Studio和Grpc.Tools自动编译

Grpc.Tools在1.17版之后,可以与MSBuild集成,自动根据proto文件编译生成C#代码。

生成的代码可以在obj/Debug/TARGET_FRAMEWORK文件夹中找到。

配置方式:

  • 添加Grpc.Tools nuget包
  • 在proto文件的属性中,将Build Action修改为Protobuf compiler
  • Build Action如果设置为Content,Custom Tool设置为MSBuild:Compile也可

注意:如果proto文件中使用了import导入其他proto文件,需要写入在Visual Studio中的完整路径,例如:

import "Protos/message.proto";复制代码

转载于:https://juejin.im/post/5ce7739a6fb9a07ec56e5245

你可能感兴趣的文章
ambassador 学习六 Module说明
查看>>
Entity Framework 复杂类型
查看>>
hibernate特殊的映射
查看>>
Mysql is null 索引
查看>>
如何查询mysql中是否表被锁
查看>>
tomcat相关配置技巧梳理
查看>>
leetcode关于数组的问题
查看>>
Linux echo 显示内容颜色
查看>>
WPF获取外部EXE图标最简单的方法
查看>>
Linux环境编写脚本安装配置JDK,Tomcat,含Tomcat自启动
查看>>
jz2440-uboot-201204版本移植【学习笔记】【原创】
查看>>
影子系统密码忘记
查看>>
windows下简单验证码识别——完美验证码识别系统
查看>>
Centos使用LVS+keepalive 搭建集群原理详解
查看>>
设计模式(33)-----行为型模式-----访问者设计模式
查看>>
模块与联系的度量(职责与协作的度量):内聚与耦合
查看>>
IBM MQ常用命令
查看>>
PIC单片机与MCS-51系列单片机的区别
查看>>
Boot Loader的启动流程和开发经验总结
查看>>
嵌入式BootLoader技术内幕(三)
查看>>