Protocol Buffers
Protocol Buffers 是 Google 的语言中立二进制序列化格式,需 .proto schema 定义,比 JSON/XML 紧凑且类型安全。
用途
提供强类型、紧凑、高效的跨语言数据交换,配合 schema 保证兼容性。
机制
用 .proto IDL 定义消息类型与字段编号。编码时每个字段以 (field_number<<3 | wire_type) 标签开头,varint 编码整数,长度前缀编码字符串与嵌套消息。未知字段向前兼容。proto3 简化语法。
用例
- gRPC 通信协议
- Google 内部数据存储
- 移动端 API(省流量)
- 配置与持久化
示例
- 输入
message User { string name = 1; }输出Binary encodingRequires protoc compilation
常见错误
- Changing field numbers breaks compatibility
- Once assigned, numbers must not be reused or changed