1 Protobuf简介
Protobuf是一种平台无关、语言无关、可扩展且轻便高效的序列化数据结构的协议,可以用于网络通信和数据存储,与msgpack类似,有名的gRPC就是基于Protobuf实现的,Protobuf3是其第三个版本。
2 Protobuf语法
2.1 定义一个消息类型
message Article {
required int32 article_id=1;
optional string article_excerpt=2;
repeated string article_picture=3;
}
2.2 字段解释(在protobuf 3中required和optional字段已经被取消)
- message是消息定义的关键字。
- required:一个格式良好的消息一定要含有1个这种字段。表示该值是必须要设置的。发送之前没有设置required字段或者无法识别required字段都会引发编解码异常,导致消息被丢弃。
- optional:消息格式中该字段可以有0个或1个值(不超过1个)。
- repeated:表示该字段可以包含0~N个元素。其特性和optional一样,但是每一次可以包含多个值。可以看作是在传递一个数组的值
- 类型
double |
| ||
float |
| ||
int32 | 使用可变长编码方式。编码负数时不够高效——如果你的字段可能含有负数,那么请使用sint32。 | ||
int64 | 使用可变长编码方式。编码负数时不够高效——如果你的字段可能含有负数,那么请使用sint64。 | ||
uint32 | Uses variable-length encoding. | ||
uint64 | Uses variable-length encoding. | ||
sint32 | 使用可变长编码方式。有符号的整型值。编码时比通常的int32高效。 | ||
sint64 | 使用可变长编码方式。有符号的整型值。编码时比通常的int64高效。 | ||
fixed32 | 总是4个字节。如果数值总是比总是比228大的话,这个类型会比uint32高效。 | ||
fixed64 | 总是8个字节。如果数值总是比总是比256大的话,这个类型会比uint64高效。 | ||
sfixed32 | 总是4个字节。 | ||
sfixed64 | 总是8个字节。 | ||
bool |
| ||
string | 一个字符串必须是UTF-8编码或者7-bit ASCII编码的文本。 | ||
bytes | 可能包含任意顺序的字节数据。 |
3 Protobuf 安装
3.1 Ubuntu
下载源码https://github.com/protocolbuffers/protobuf/releases
make
make check
make install
有可能找不到库文件
root@dotz-pc:~/protobuf-3.7.0# protoc
protoc: error while loading shared libraries: libprotoc.so.18: cannot open shared object file: No such file or directory
只需将/usr/local/lib加入到默认库
root@dotz-pc:~/protobuf-3.7.0# echo "/usr/local/lib" >> /etc/ld.so.conf
root@dotz-pc:~/protobuf-3.7.0# /sbin/ldconfig
3.2 MacOS
brew update
brew install protobuf
3.3 支持golang
go get -u github.com/golang/protobuf/protoc-gen-go
4 Protobuf 使用
https://blog.csdn.net/idwtwt/article/details/80400598