protobuf 常用使用注意
Table of Contents
proto 中,所有结构化的数据都为 message
message demo {
required int32 id = 1; //id
required string str = 2; //str
optional int32 opt = 3; //optional field
}
开头第一行不申明 syntax = "proto3";~,则默认使用 ~proto2 进行解析
syntax = "proto3"; ...
每个消息定义的每个字段都有唯一的编号。
范围 1 到 15 的字段编号需要一个字节进行编码,包括字段编号和字段类型。范围 16 ~ 2047 中的字段编号需要两个
字节。所以 1 ~ 15 作为非常频繁出现的消息元素。
不能在同一个 reserved 语句中混合字段名称和字段编号
message Test {
reserved 1, 2, 5 to 12;
reserved "age", "addr";
}
各种语言标量类型对应
| proto | C++ | Java | Python | Go | C# | PHP |
| double | double | double | float | float64 | double | float |
| float | float | float | floata | float32 | float | float |
| int32 | int32 | int | int | int32 | int | integer |
| int64 | int64 | long | int/long | int64 | long | integer/string |
| uint32 | uint32 | int | int/long | uint32 | uint | integer |
| uint64 | uint64 | long | int/long | uint64 | ulong | integer/string |
| sint32 | int32 | int | int | int32 | int | integer |
| sint64 | int64 | long | int/long | int64 | long | integer/string |
| fixed32 | uint32 | int | int/long | uint32 | uint | integer |
| fixed64 | uint64 | long | int/long | uint64 | ulong | integer/string |
sfixed32 | int32 | int | int | int32 | int | integer |
| sfixed64 | int64 | long | int/long | int64 | long | integer/string |
| bool | bool | boolean | bool | bool | bool | boolean |
| string | string | string | str/unicode | string | string | string |
| bytes | string | ByteString | str | []byte | ByteString | string |
> php integer/string 注意,64位计算机用 integer,32位用 string
枚举类型一定要有 0 值
枚举为 0 的是作为零值,当不赋值的时候,就会是零值
为了和 proto2 兼容。在 proto2 中,零值必须是第一个值。
map 类型不能用 repeated 修饰
map<k_type, v_type> map_field = N; example: map<string, Demo> demos = 3;
JSON Mapping
proto3 支持 JSON 中的规范编码
| proto3 | JSON | JSON example |
| message | object | {"name":"josephzeng" …} |
| enum | string | "F_A" |
| map<K,V> | object | {"k" :"v" …} |
| repeated V | array | {v …} |
| bool | true, false | true, false |
| string | string | "josephzeng" |
| bytes | base64, string | "ABDSFSDFDS" |
| int32, fixed32, uint32 | number | 1 … |
| int64, fixed64, uint64 | string | "1" … |
| float, double | number | 1.1 … |
| Any | object | {…} |
| Timestamp | string | "2012-01-01" … |
| struct | object | {…} |
| Value | value | JSON value |
| NullValue | null | JSON null |
常见命名规范
- message 采用骆驼峰,首字母大写,字段采用下划线
message DemoReq {
required string my_name = 1;
}
- 枚举类型采用骆驼峰,首字母大写,字段采用下划线及大写,枚举值分号结束
enum A {
F_VAL = 0;
S_VAL = 1;
}
持续更新