引言
google protocol buffer :一个语言无关,平台无关,可扩展的结构化数据序列化的方法,可用于通信协议,数据存储等;
(protocol buffers – a language-neutral, platform-neutral, extensible way of serializing structured data for use in communications protocols, data storage, and more.)
1.什么是google protocol buffer
- protocol buffer 是一个灵活、高效、自动的序列化结构化数据的方法,功能上类似于XML,但更小、更快、更简单;
- 开发者定于数据结构,使用protobuf的代码生成器生成代码实现不同数据流的读写;
- 向后兼容性好:在不破坏已部署的、依靠“老”数据结构的程序就可以对数据结构升级;这样程序就不会因为消息结构的改变而造成的大规模的代码重构或者迁移的问题。因为新添加的filed 并不会引起已经发布的程序的任何改变;
2.使用protobuf的开发流程
- 定义消息结构:编辑 .proto文件;以定义person.proto为例:
message Person { required string name = 1; required int32 id = 2; optional string email = 3; enum PhoneType { MOBILE = 0; HOME = 1; WORK = 2; } message PhoneNumber { required string number = 1; optional PhoneType type = 2 [default = HOME]; } repeated PhoneNumber phone = 4; }
- 使用protobuf提供的代码生成器生成CLASS Person类的头文件及其实现:message.person.h, message.person.cc;
- 使用提供的accessors即可实现消息体各个字段的读写:query();set_query();
- 下面是一个典型的结构化数据person先写入一个文件中再从文件中读出的demo:
Person person; person.set_name("John Doe"); person.set_id(1234); person.set_email("jdoe@example.com"); fstream output("myfile", ios::out | ios::binary); person.SerializeToOstream(&output);
fstream input("myfile", ios::in | ios::binary); Person person; person.ParseFromIstream(&input); cout << "Name: " << person.name() << endl; cout << "E-mail: " << person.email() << endl;
- 可以在message中增加新的filed,已有的message解析模块会兼容;
- 小3-10倍;
- 快20-100倍;
- 歧义性更少;
- 简单;
- 自动将结构化数据序列化和发序列化;
- RPC系统;