阅读protobuf文档
This commit is contained in:
45
protobuf/protobuf.md
Normal file
45
protobuf/protobuf.md
Normal file
@@ -0,0 +1,45 @@
|
||||
- [protobuf](#protobuf)
|
||||
- [language guide(proto3)](#language-guideproto3)
|
||||
- [定义message type](#定义message-type)
|
||||
- [Assign Field Numbers](#assign-field-numbers)
|
||||
- [重复使用filed number的后果](#重复使用filed-number的后果)
|
||||
|
||||
|
||||
# protobuf
|
||||
## language guide(proto3)
|
||||
### 定义message type
|
||||
如下为一个定义search request message format的示例,
|
||||
```proto
|
||||
synatx="proto3"
|
||||
|
||||
message SearchRequest {
|
||||
string query = 1;
|
||||
int32 page_number = 2;
|
||||
int32 results_per_page = 3;
|
||||
}
|
||||
```
|
||||
上述示例含义如下:
|
||||
- `synatx = "proto3"`:
|
||||
- 代表当前protobuf的language版本为`proto3`
|
||||
- 如果没有指定`syntax`,那么protocol buffer compiler默认会假设在使用`proto2`
|
||||
- `Search Request`消息定义了3个fields,每个field都代表`希望包含在message中的一部分数据`
|
||||
|
||||
### Assign Field Numbers
|
||||
可以为message中的每个field定义一个整数,范围为`[1,536,870,911]`,并有如下约束
|
||||
- message中所有field的给定数字必须唯一
|
||||
- field number `[19,000, 19,999]`是为`Protocol Buffer`实现保留的,如果使用这些数字,protocol buffer compiler将会报错
|
||||
|
||||
一旦消息类型被使用后,field number就不能被改变,field number代表message wire format中的field。
|
||||
|
||||
如果对field的field number进行了修改,代表删除旧的field并且新建一个相同类型的field。
|
||||
|
||||
filed number不应该被重用。
|
||||
|
||||
对于`频繁被设置`的fields,应该将其的field number设置为`[1,15]`。在wire format中,field number的值越小占用空间越小。
|
||||
|
||||
> 例如,`[1,15]`在编码时只占用1字节,而`[16, 2047]`则会占用2字节。
|
||||
|
||||
### 重复使用filed number的后果
|
||||
如果重复使用field number,将会造成解码wire-format message的二义性。
|
||||
|
||||
protobuf wire format
|
||||
Reference in New Issue
Block a user