Protocol Buffers 官方给出的一些使用建议、部分细节说明以及一些配套工具介绍记录在这里。
入门教程 Protocol Buffers Tutorials,协议语法要点见 tag: protobuf。
Style Guide 是 Protocol Buffers 给出的风格建议。
1. License header (if applicable)
2. File overview
3. Syntax
4. Package
5. Imports (sorted)
6. File options
7. Everything else
message SongServerRequest {
optional string song_name = 1;
}
enum FooBar {
FOO_BAR_UNSPECIFIED = 0;
FOO_BAR_FIRST_VALUE = 1;
FOO_BAR_SECOND_VALUE = 2;
}
service FooService {
rpc GetSomething(GetSomethingRequest) returns (GetSomethingResponse);
rpc ListSomething(ListSomethingRequest) returns (ListSomethingResponse);
}
Design Patterns for Dealing with Protocol Buffers 给出了部分场景下的使用说明/建议。
Protobuf Buffers 不适合传输大段数据,如果需要发送的 message 超过 1MB,需要考虑使用其它方式。
可以用下面的方式实现自描述的消息(Google 内部没有遇到需要使用自描述消息的情形):
syntax = "proto3";
import "google/protobuf/any.proto";
import "google/protobuf/descriptor.proto";
message SelfDescribingMessage {
// Set of FileDescriptorProtos which describe the type and its dependencies.
google.protobuf.FileDescriptorSet descriptor_set = 1;
// The message and its type, encoded as an Any message.
google.protobuf.Any message = 2;
}
Protocol Buffer Wire Format 介绍了 protobuf 的编码方式,即二进制格式, 按需了解。
Protocol Buffers 自带的编译命令 protoc 能够对接第三方插件:Compiler Plugins 。
Protocol Buffers 提供了多种编程语言的 runtime:Protobuf Runtime。
此外还有很多第三方项目,提供了对更多编程语言的多种支持方式以及更多的 rpc 框架,统一收录在:Third-Party Add-ons。
protoc 的 Compiler Plugins 功能,可以用 --plugin
参数指定第三方插件:
--plugin=EXECUTABLE Specifies a plugin executable to use.
Normally, protoc searches the PATH for
plugins, but you may specify additional
executables not in the path using this flag.
Additionally, EXECUTABLE may be of the form
NAME=PATH, in which case the given plugin name
is mapped to the given executable even if
the executable's own name differs.
Programming Languages Support 中收录的项目基本都提供了各自的 complier plugin。比如 github.com/golang/protobuf 中实现的 protoc-gen-go 是默认的 Go 语言代码生成插件,下面的命令会默认到 $PATH 路径中寻找 protoc-gen-go 命令。
protoc --go_out=paths=source_relative:. path/to/file.proto
支持 Protobuf 的 RPC 框架很多(RPC Implementations):