在LINUX上安装protobuf
apt install -y protobuf-compiler protoc --version # 确定版本号在3以上
如果上面的方法不行,用下面的
安装预编译的protobuf二进制文件
- 从github.com/google/protobuf/releases手动下载对应于你的操作系统和计算机体系结构 ( protoc--.zip)的 zip 文件,或使用如下命令获取该文件:
$ PB_REL="https://github.com/protocolbuffers/protobuf/releases" $ curl -LO $PB_REL/download/v3.15.8/protoc-3.15.8-linux-x86_64.zip
- 将文件解压缩到$HOME/.local你选择的目录下。例如:
$ unzip protoc-3.15.8-linux-x86_64.zip -d $HOME/.local
- 更新环境的路径变量以包含protoc可执行文件的路径 。例如:
$ export PATH="$PATH:$HOME/.local/bin"
协议编译器的Go 插件
- 使用以下命令为 Go 安装协议编译器插件:
$ go install google.golang.org/protobuf/cmd/protoc-gen-go@v1.26 $ go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@v1.1
- 更新你的PATH以便protoc编译器可以找到插件:
$ export PATH="$PATH:$(go env GOPATH)/bin"
获取示例代码
示例代码是grpc-go 的一部分 。
- 将 repo 下载为 zip 文件 并解压缩它,或克隆 repo:
$ git clone -b v1.41.0 https://github.com/grpc/grpc-go
- 切换到快速入门示例目录:
$ cd grpc-go/examples/helloworld
运行示例
从examples/helloworld目录:
- 编译并执行服务器代码:(运行后待机)
$ go run greeter_server/main.go
- 从不同的终端编译并执行客户端代码以查看客户端输出:
$ go run greeter_client/main.go Greeting: Hello world
恭喜!你刚刚使用 gRPC 运行了一个客户端-服务器应用程序
更新GRPC服务
修改.proto文件
打开helloworld/helloworld.proto并添加一个SayHelloAgain()具有相同请求和响应类型的新方法:
// The greeting service definition. service Greeter { // Sends a greeting rpc SayHello (HelloRequest) returns (HelloReply) {} // Sends another greeting rpc SayHelloAgain (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; }
保存文件
重新生成 gRPC 代码
在您可以使用新的服务方法之前,您需要重新编译更新的 .proto文件。
仍在examples/helloworld目录中时,运行以下命令:
$ protoc --go_out=. --go_opt=paths=source_relative \ --go-grpc_out=. --go-grpc_opt=paths=source_relative \ helloworld/helloworld.proto
这将重新生成helloworld/helloworld.pb.go和helloworld/helloworld_grpc.pb.go文件,其中包含:
- 代码填充,序列化和检索
- HelloRequest
- 和
- HelloReply
- 信息类型。
- 生成客户端和服务器代码。
如果失败了,提示无法识别--go_opt
更新protoc到最新版
如果提示缺少protoc-gen-go
从protobuf-master下载压缩包,解压后进入protoc-gen-go文件夹执行
go build
之后将编译出来的protoc-gen-go放入go执行目录
如果提示缺少protoc-gen-go-grpc
从grpc-go-master下载压缩包,解压后进入cmd/protoc-gen-go-grpc文件夹执行
go build
之后将编译出来的protoc-gen-go-grpc放入go执行目录