现在的位置: 首页 > 综合 > 正文

玩转Protocol Buffers

2013年08月15日 ⁄ 综合 ⁄ 共 1539字 ⁄ 字号 评论关闭

1. 人人都爱Protocol Buffers

1.1 Protocol Buffers(PB)是什么?

Protocol buffers are Google’s language-neutral, platform-neutral, extensible mechanism for serializing structured data – think XML, but smaller, faster, and simpler. You define how you want your data to be structured
once, then you can use special generated source code to easily write and read your structured data to and from a variety of data streams and using a variety of languages – Java, C++, or Python. You can even update your data structure without breaking deployed
programs that are compiled against the “old” format.(摘自PB官网

针对英文不太好的同学,除了强烈建议好好学一下英文外(PB的最新文档总是英文的),这里笔者按照自己的理解试着翻译一下:protocol buffers是google提供的一种将结构化数据进行序列化和反序列化的方法,其优点是语言中立,平台中立,可扩展性好,目前在google内部大量用于数据存储,通讯协议等方面。PB在功能上类似XML,但是序列化后的数据更小,解析更快,使用上更简单。用户只要按照proto语法在.proto文件中定义好数据的结构,就可以使用PB提供的工具(protoc)自动生成处理数据的代码,使用这些代码就能在程序中方便的通过各种数据流读写数据。PB目前支持Java,
C++和Python3种语言。另外,PB还提供了很好的向后兼容,即旧版本的程序可以正常处理新版本的数据,新版本的程序也能正常处理旧版本的数据。

1.2 如何使用Protocol Buffers?

这里以官网Tutorial通讯簿例子来简单介绍一下PB的常规使用方式,非常规的使用方式在后面几章逐一介绍

1.在addressbook.proto文件里定义通讯簿消息的格式,一个通讯簿(AddressBook)由可重复的Person组成,一个person由两个必需存在的name和id字段,以及一个可选的email字段,和可重复的PhoneNumber构成。PhoneNumber由number和type组成。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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;
}
 
message
AddressBook {
  repeated
Person person = 1;
}

2.使用PB提供的工具 protoc根据.proto文件自动生成处理消息的代码

1
protoc
-I=$SRC_DIR --cpp_out=$DST_DIR $SRC_DIR/addressbook.proto
1
2
3
4
5

抱歉!评论已关闭.