4.6 gRPC 和 Protobuf 扩展

目前开源社区已经围绕 Protobuf 和 gRPC 开发出众多扩展,形成了庞大的生态。本节我们将简单介绍验证器和 REST 接口扩展。

4.6.1 验证器

到目前为止,我们接触的全部是第三版的 Protobuf 语法。第二版的 Protobuf 有个默认值特性,可以为字符串或数值类型的成员定义默认值。

我们采用第二版的 Protobuf 语法创建文件:

  1. syntax = "proto2";
  2. package main;
  3. message Message {
  4. optional string name = 1 [default = "gopher"];
  5. optional int32 age = 2 [default = 10];
  6. }

内置的默认值语法其实是通过 Protobuf 的扩展选项特性实现。在第三版的 Protobuf 中不再支持默认值特性,但是我们可以通过扩展选项自己模拟默认值特性。

下面是用 proto3 语法的扩展特性重新改写上述的 proto 文件:

  1. syntax = "proto3";
  2. package main;
  3. import "google/protobuf/descriptor.proto";
  4. extend google.protobuf.FieldOptions {
  5. string default_string = 50000;
  6. int32 default_int = 50001;
  7. }
  8. message Message {
  9. string name = 1 [(default_string) = "gopher"];
  10. int32 age = 2[(default_int) = 10];
  11. }

其中成员后面的方括号内部的就是扩展语法。重新生成 Go 语言代码,里面会包含扩展选项相关的元信息:

  1. var E_DefaultString = &proto.ExtensionDesc{
  2. ExtendedType: (*descriptor.FieldOptions)(nil),
  3. ExtensionType: (*string)(nil),
  4. Field: 50000,
  5. Name: "main.default_string",
  6. Tag: "bytes,50000,opt,name=default_string,json=defaultString",
  7. Filename: "helloworld.proto",
  8. }
  9. var E_DefaultInt = &proto.ExtensionDesc{
  10. ExtendedType: (*descriptor.FieldOptions)(nil),
  11. ExtensionType: (*int32)(nil),
  12. Field: 50001,
  13. Name: "main.default_int",
  14. Tag: "varint,50001,opt,name=default_int,json=defaultInt",
  15. Filename: "helloworld.proto",
  16. }

我们可以在运行时通过类似反射的技术解析出 Message 每个成员定义的扩展选项,然后从每个扩展的相关联的信息中解析出我们定义的默认值。

在开源社区中,github.com/mwitkow/go-proto-validators 已经基于 Protobuf 的扩展特性实现了功能较为强大的验证器功能。要使用该验证器首先需要下载其提供的代码生成插件:

  1. $ go get github.com/mwitkow/go-proto-validators/protoc-gen-govalidators

然后基于 go-proto-validators 验证器的规则为 Message 成员增加验证规则:

  1. syntax = "proto3";
  2. package main;
  3. import "github.com/mwitkow/go-proto-validators/validator.proto";
  4. message Message {
  5. string important_string = 1 [
  6. (validator.field) = {regex: "^[a-z]{2,5}$"}
  7. ];
  8. int32 age = 2 [
  9. (validator.field) = {int_gt: 0, int_lt: 100}
  10. ];
  11. }

在方括弧表示的成员扩展中,validator.field 表示扩展是 validator 包中定义的名为 field 扩展选项。validator.field 的类型是 FieldValidator 结构体,在导入的 validator.proto 文件中定义。

所有的验证规则都由 validator.proto 文件中的 FieldValidator 定义:

  1. syntax = "proto2";
  2. package validator;
  3. import "google/protobuf/descriptor.proto";
  4. extend google.protobuf.FieldOptions {
  5. optional FieldValidator field = 65020;
  6. }
  7. message FieldValidator {
  8. // Uses a Golang RE2-syntax regex to match the field contents.
  9. optional string regex = 1;
  10. // Field value of integer strictly greater than this value.
  11. optional int64 int_gt = 2;
  12. // Field value of integer strictly smaller than this value.
  13. optional int64 int_lt = 3;
  14. // ... more ...
  15. }

从 FieldValidator 定义的注释中我们可以看到验证器扩展的一些语法:其中 regex 表示用于字符串验证的正则表达式,int_gt 和 int_lt 表示数值的范围。

然后采用以下的命令生成验证函数代码:

  1. protoc \
  2. --proto_path=${GOPATH}/src \
  3. --proto_path=${GOPATH}/src/github.com/google/protobuf/src \
  4. --proto_path=. \
  5. --govalidators_out=. --go_out=plugins=grpc:.\
  6. hello.proto

windows: 替换 ${GOPATH}%GOPATH% 即可.

以上的命令会调用 protoc-gen-govalidators 程序,生成一个独立的名为 hello.validator.pb.go 的文件:

  1. var _regex_Message_ImportantString = regexp.MustCompile("^[a-z]{2,5}$")
  2. func (this *Message) Validate() error {
  3. if !_regex_Message_ImportantString.MatchString(this.ImportantString) {
  4. return go_proto_validators.FieldError("ImportantString", fmt.Errorf(
  5. `value '%v' must be a string conforming to regex "^[a-z]{2,5}$"`,
  6. this.ImportantString,
  7. ))
  8. }
  9. if !(this.Age> 0) {
  10. return go_proto_validators.FieldError("Age", fmt.Errorf(
  11. `value '%v' must be greater than '0'`, this.Age,
  12. ))
  13. }
  14. if !(this.Age < 100) {
  15. return go_proto_validators.FieldError("Age", fmt.Errorf(
  16. `value '%v' must be less than '100'`, this.Age,
  17. ))
  18. }
  19. return nil
  20. }

生成的代码为 Message 结构体增加了一个 Validate 方法,用于验证该成员是否满足 Protobuf 中定义的条件约束。无论采用何种类型,所有的 Validate 方法都用相同的签名,因此可以满足相同的验证接口。

通过生成的验证函数,并结合 gRPC 的截取器,我们可以很容易为每个方法的输入参数和返回值进行验证。

4.6.2 REST 接口

gRPC 服务一般用于集群内部通信,如果需要对外暴露服务一般会提供等价的 REST 接口。通过 REST 接口比较方便前端 JavaScript 和后端交互。开源社区中的 grpc-gateway 项目就实现了将 gRPC 服务转为 REST 服务的能力。

grpc-gateway 的工作原理如下图:

4.6 gRPC 和 Protobuf 扩展 - 图1

图 4-2 gRPC-Gateway 工作流程

通过在 Protobuf 文件中添加路由相关的元信息,通过自定义的代码插件生成路由相关的处理代码,最终将 REST 请求转给更后端的 gRPC 服务处理。

路由扩展元信息也是通过 Protobuf 的元数据扩展用法提供:

  1. syntax = "proto3";
  2. package main;
  3. import "google/api/annotations.proto";
  4. message StringMessage {
  5. string value = 1;
  6. }
  7. service RestService {
  8. rpc Get(StringMessage) returns (StringMessage) {
  9. option (google.api.http) = {
  10. get: "/get/{value}"
  11. };
  12. }
  13. rpc Post(StringMessage) returns (StringMessage) {
  14. option (google.api.http) = {
  15. post: "/post"
  16. body: "*"
  17. };
  18. }
  19. }

我们首先为 gRPC 定义了 Get 和 Post 方法,然后通过元扩展语法在对应的方法后添加路由信息。其中 “/get/{value}” 路径对应的是 Get 方法,{value} 部分对应参数中的 value 成员,结果通过 json 格式返回。Post 方法对应 “/post” 路径,body 中包含 json 格式的请求信息。

然后通过以下命令安装 protoc-gen-grpc-gateway 插件:

  1. go get -u github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway

再通过插件生成 grpc-gateway 必须的路由处理代码:

  1. $ protoc -I/usr/local/include -I. \
  2. -I$GOPATH/src \
  3. -I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \
  4. --grpc-gateway_out=. --go_out=plugins=grpc:.\
  5. hello.proto

windows: 替换 ${GOPATH}%GOPATH% 即可.

插件会为 RestService 服务生成对应的 RegisterRestServiceHandlerFromEndpoint 函数:

  1. func RegisterRestServiceHandlerFromEndpoint(
  2. ctx context.Context, mux *runtime.ServeMux, endpoint string,
  3. opts []grpc.DialOption,
  4. ) (err error) {
  5. ...
  6. }

RegisterRestServiceHandlerFromEndpoint 函数用于将定义了 Rest 接口的请求转发到真正的 gRPC 服务。注册路由处理函数之后就可以启动 Web 服务了:

  1. func main() {
  2. ctx := context.Background()
  3. ctx, cancel := context.WithCancel(ctx)
  4. defer cancel()
  5. mux := runtime.NewServeMux()
  6. err := RegisterRestServiceHandlerFromEndpoint(
  7. ctx, mux, "localhost:5000",
  8. []grpc.DialOption{grpc.WithInsecure()},
  9. )
  10. if err != nil {
  11. log.Fatal(err)
  12. }
  13. http.ListenAndServe(":8080", mux)
  14. }

启动 grpc 服务 , 端口 5000

  1. type RestServiceImpl struct{}
  2. func (r *RestServiceImpl) Get(ctx context.Context, message *StringMessage) (*StringMessage, error) {
  3. return &StringMessage{Value: "Get hi:" + message.Value + "#"}, nil
  4. }
  5. func (r *RestServiceImpl) Post(ctx context.Context, message *StringMessage) (*StringMessage, error) {
  6. return &StringMessage{Value: "Post hi:" + message.Value + "@"}, nil
  7. }
  8. func main() {
  9. grpcServer := grpc.NewServer()
  10. RegisterRestServiceServer(grpcServer, new(RestServiceImpl))
  11. lis, _ := net.Listen("tcp", ":5000")
  12. grpcServer.Serve(lis)
  13. }

首先通过 runtime.NewServeMux() 函数创建路由处理器,然后通过 RegisterRestServiceHandlerFromEndpoint 函数将 RestService 服务相关的 REST 接口中转到后面的 gRPC 服务。grpc-gateway 提供的 runtime.ServeMux 类也实现了 http.Handler 接口,因此可以和标准库中的相关函数配合使用。

当 gRPC 和 REST 服务全部启动之后,就可以用 curl 请求 REST 服务了:

  1. $ curl localhost:8080/get/gopher
  2. {"value":"Get: gopher"}
  3. $ curl localhost:8080/post -X POST --data '{"value":"grpc"}'
  4. {"value":"Post: grpc"}

在对外公布 REST 接口时,我们一般还会提供一个 Swagger 格式的文件用于描述这个接口规范。

  1. $ go get -u github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger
  2. $ protoc -I. \
  3. -I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \
  4. --swagger_out=. \
  5. hello.proto

然后会生成一个 hello.swagger.json 文件。这样的话就可以通过 swagger-ui 这个项目,在网页中提供 REST 接口的文档和测试等功能。

4.6.3 Nginx

最新的 Nginx 对 gRPC 提供了深度支持。可以通过 Nginx 将后端多个 gRPC 服务聚合到一个 Nginx 服务。同时 Nginx 也提供了为同一种 gRPC 服务注册多个后端的功能,这样可以轻松实现 gRPC 负载均衡的支持。Nginx 的 gRPC 扩展是一个较大的主题,感兴趣的读者可以自行参考相关文档。