1 定义:
Protocol buffers are a language-neutral, platform-neutral extensible mechanism for serializing structured data.
2 编译protobuf
- 安装Protob Compiler
- 安装Go CodeGen 组件
- Download go code generator: https://github.com/protocolbuffers/protobuf-go/tree/v1.24.0/cmd/protoc-gen-go
- put it under %userprofile%/go/src/google.golang.org/protobuf
- run cmd "go install google.golang.org/protobuf/cmd/protoc-gen-go"
- Check( %userprofile%goinprotoc-gen-go )file existed
- 安装Go gRPC CodeGen组件
- Download gRPC Code generator from https://github.com/grpc/grpc-go
- Put it under %userprofile%/go/src/google.golang.org/protobuf
- Run ( go install "google.golang.org/grpc/cmd/protoc-gen-go-grpc" ) to install grpc. For dependencies
- golang.org/x/net : https://github.com/golang/net . Download and put it to %userprofile%/go/src/golang.org/x/ and Run (go install "golang.org/x/net")
- google.golang.org/genproto: https://github.com/googleapis/go-genproto. Donwloand and out it to %userprofile%/go/src/google.golang.org/ and run (go install "google.golang.org/genproto/googleapis/rpc/status")
- golang.org/x/text: https://github.com/golang/text. Download and put it to %userprofile%/go/src/golang.org/x/ and Run (go install "golang.org/x/text")
3 开发Protobuf原型
3.1 开发 protob 数据文件文件。
参照https://developers.google.com/protocol-buffers
1. 注意声明go_package是必须的,定义了package的位置 option go_package = "/model";
2. 生成Go文件。命令行
protoc -I=e:/Git/go/src/proto --go_out=e:/Git/go/src/gen e:/Git/go/src/proto/address.proto 生成*.pb.go 文件。
结合1、2 工程目录下会生成 src/gen/model/*.pb.go 文件,此文件即为可以复用的go文件
3.2 开发 gRPC 的protobuf文件
1. 注意声明go_package是必须的,定义了package的位置 option go_package = "/service";
2. 生成Go文件。命令行
protoc -I=e:/Git/go/src/proto --go_out=e:/Git/go/src/gen --go-grpc_out=e:/Git/go/src/gen e:/Git/go/src/proto/service.proto
结合1、2 工程目录下会生成 src/gen/service/*.pb.go 文件,此文件即为可以复用的go文件
3.3 开发简单的gRPC 客户端、服务端
实例:https://grpc.io/docs/languages/go/quickstart/
- 注意Server、client要引用Service使用绝对路径。 如
import { pb "./gen/service" }
p := pb.Person{ Id: 1234, Name: "John Doe", Email: "jdoe@example.com", Phones: []*pb.Person_PhoneNumber{ {Number: "555-4321", Type: pb.Person_HOME}, }, }