Protocol buffers 是 Google 的一种语言中立、平台中立,可扩展,用于序列化结构化数据的交互式数据语言。相比 JSON、XML,它更小、更快、更简单。
定义一个消息类型: 新建一个 user.proto 文件:
syntax = "proto3";
package message;
message UserRequest {
int64 uid = 1;
string username = 2;
}
字段编号从 1 到 2^29 - 1(536,870,911),不可使用预留字段编号 19000-19999,其中 1-15 占用 1 字节,应该用于频繁出现的字段。
在一个.proto文件中,可以定义多个消息类型。
Protobuf 生成的数据类型与原始类型并不完全一致,该表格展示了定义于 .proto 文件中的类型,以及与之对应的、在自动生成的访问类中定义的类型:
.proto Type | Notes | Go Type |
---|---|---|
double | float64 | |
float | float32 | |
int32 | 使用变长编码,对于负值的效率很低,如果你的域有可能有负值,请使用sint32替代。 | int32 |
int64 | 使用变长编码,对于负值的效率很低,如果你的域有可能有负值,请使用sint64替代。 | int64 |
uint32 | 使用变长编码。 | uint32 |
uint64 | 使用变长编码。 | uint64 |
sint32 | 使用变长编码,这些编码在负值时比int32高效的多。 | int32 |
sint64 | 使用变长编码,这些编码在负值时比int64高效的多。 | int64 |
fixed32 | 总是4个字节,如果数值总是比总是比228大的话,这个类型会比uint32高效。 | uint32 |
续:
fixed64 | 总是8个字节,如果数值总是比总是比256大的话,这个类型会比uint64高效。 | uint64 |
---|---|---|
sfixed32 | 总是4个字节。 | int32 |
sfixed64 | 总是8个字节。 | int64 |
bool | bool | |
string | 一个字符串必须是UTF-8编码或者7-bit ASCII编码的文本。 | string |
bytes | 可能包含任意顺序的字节数据。 | []byte |
限于篇幅,如需了解上述内容,请阅读文档。
官方文档: https://developers.google.com/protocol-buffers/docs/proto3
中文翻译:
https://colobu.com/2017/03/16/Protobuf3-language-guide
protoc 是 Protobuf 的编译器,结合插件将我们编写的 .proto 文件编译成我们需要的编程语言代码。
注意:安装过程中,可能会提示需要依赖库,可以根据错误提示安装依赖库。另外,如果你使用的是 macOS,系统已经预装了 protoc,无需重复安装。
protoc-gen-go(Go 代码生成插件)
proto 包提供了操作 protobuf 的一系列函数,其中序列化和反序列化函数比较常用,用来将数据序列化后进行传递。
序列化:
func proto.Marshal(m protoiface.MessageV1) ([]byte, error)
Marshal returns the wire-format encoding of m.
反序列化:
func proto.Unmarshal(b []byte, m protoreflect.ProtoMessage) error
Unmarshal parses the wire-format message in b and places the result in m.
更多关于 proto 包的函数使用方法,请查阅文档:
https://pkg.go.dev/google.golang.org/protobuf/proto
本文简单描述了 protobuf 的基本语法,如何安装 protoc 和 protoc 插件 protoc-gen-go,如何将 .proto 文件编译成 go 文件。通过阅读本文,读者应该可以完成编写.proto文件,并使用 protoc 编译器和插件生成 go 文件。