安装 protobuf 编译环境
gRPC 服务使用 protobuf 作为序列化协议, 下面介绍在 Linux 系统下如何安装 protobuf 编译环境
安装 protoc
下载并解压
wget -O /tmp/protoc-21.1-linux-x86_64.zip https://github.com/protocolbuffers/protobuf/releases/download/v21.1/protoc-21.1-linux-x86_64.zip
unzip -d /usr/local/protoc /tmp/protoc-21.1-linux-x86_64.zip
添加系统路径
echo "export PATH=\$PATH:/usr/local/protoc/bin" >> ~/.bashrc
source ~/.bashrc
测试是否安装成功
protoc --version
安装 Go 插件
go install google.golang.org/protobuf/cmd/protoc-gen-go@v1.28.0
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@v1.2.0
go install github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway@v1.15.2
go install github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger@v1.15.2
go install github.com/gogo/protobuf/protoc-gen-gogofaster@v1.3.2
编译 proto 文件
创建 helloworld/helloworld.proto 文件, 写入如下内容
syntax = "proto3";
option go_package = "google.golang.org/grpc/examples/helloworld/helloworld";
package helloworld;
service Greeter {
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
message HelloRequest {
string name = 1;
}
message HelloReply {
string message = 1;
}
编译 proto 源文件为 Go 代码
protoc --go_out=. --go_opt=paths=source_relative \
--go-grpc_out=. --go-grpc_opt=paths=source_relative \
helloworld/helloworld.proto