Mecanim 发表于 2021-10-13 14:04

51.Go Protobuf

介绍
Protobuf或协议缓冲区对数据进行编码和解码,以便以不同语言编写的不同应用程序或模块可以快速而可靠地交换大量消息,而不会导致通信通道过载。 使用protobuf,其性能与你倾向于发送的消息数量成正比。 通过为你提供工具以在源处对消息进行编码并在目标处对消息进行解码,它将压缩要发送的消息为序列化的二进制格式。

备注
使用protobuf有两个步骤。

首先,你必须编译协议缓冲区定义
将以上定义以及支持库导入到你的程序中。
gRPC支持

如果proto文件指定了RPC服务,则可以指示protoc-gen-go生成与gRPC(http://www.grpc.io/)兼容的代码。 为此,请将plugins参数传递给protoc-gen-go; 通常的方法是将其插入到protoc的–go_out参数中:

$ protoc --go_out=plugins=grpc:. *.proto
在Go中使用Protobuf


你想要序列化并发送的消息可以包含在文件test.proto中,其中包含
package example;enum FOO { X = 17; };message Test {    required string label = 1;    optional int32 type = 2 ;    repeated int64 reps = 3;    optional group OptionalGroup = 4 {    required string RequiredField = 5;    }}
要编译协议缓冲区定义,请在将–go_out参数设置为要将Go代码输出到的目录下运行protoc。

$ protoc --go_out=. *.proto

要从示例包创建并使用Test对象:
package mainimport (    "log"    "github.com/golang/protobuf/proto"    "path/to/example")func main() {    test := &example.Test {      Label: proto.String("hello"),      Type:proto.Int32(17),      Reps:[]int64{1, 2, 3},      Optionalgroup: &example.Test_OptionalGroup {            RequiredField: proto.String("good bye"),      },    }    data, err := proto.Marshal(test)    if err != nil {      log.Fatal("marshaling error: ", err)    }    newTest := &example.Test{}    err = proto.Unmarshal(data, newTest)    if err != nil {      log.Fatal("unmarshaling error: ", err)    }    // Now test and newTest contain the same data.    if test.GetLabel() != newTest.GetLabel() {      log.Fatalf("data mismatch %q != %q", test.GetLabel(), newTest.GetLabel())    }    // etc.}
要将额外的参数传递给插件,请使用逗号分隔的参数列表,该列表与输出目录之间用冒号分隔:

$ protoc --go_out=plugins=grpc,import_path=mypackage:. *.proto
页: [1]
查看完整版本: 51.Go Protobuf