[转]Google Protocol Buffers 2.4

来源:互联网 发布:手机跟踪定位器软件 编辑:程序博客网 时间:2024/05/21 07:36

一篇别人实践过的Protocol Buffers的东东。

 

转自: http://blog.in88.com/2011/03/protobuf/

 

Google protocol buffers – a language-neutral, platform-neutral, extensible way of serializing structured data.

Google的定义是:用于序列化结构化的数据的跨语言、跨平台的可扩展机制。其实就是和XML类似,不过ProtoBuf的尺寸要小3-10倍,解析速度要快20-100倍。同时和Hessian、Java 序列化有所不同的是, ProtoBuf可以用通过定义好数据结构的 proto ( IDL )文件产生目标语言代码,大大减少了开发量。

1、下载protoc-2.4.0-win32.zip(Binary)和protobuf-2.4.0a.zip(source)

http://code.google.com/p/protobuf/downloads/list

2、解压缩protoc-2.4.0-win32.zip获得protoc.exe

3、编写数据结构文件addressbook.proto,

参考http://code.google.com/intl/zh-CN/apis/protocolbuffers/docs/proto.html

—————————————–

option java_package = “protobuf”;

option java_outer_classname = “AddressBookProtos”;



message Person {

required string name = 1;

required int32 id = 2; // Unique ID number for this person.

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;

}

—————————————–

4、生成java代码:protoc addressbook.proto –-java_out=gen

可以获得protobuf/AddressBookProtos.java

5、将protobuf-2.4.0a.zip中的java/src/main/java/*.*加入到Eclipse项目中,发现有“DescriptorProto cannot be resolved to a type”错误,需要获得src/google/protobuf/descriptor.proto,生成descriptor的代码“protoc descriptor.proto –-java_out=src”。

6、通过Eclipse的Expert JAR file功能,生成protobuf-2.4.jar,方便以后使用。

7、将AddressBookProtos.java加入到Eclipse中,添加protobuf-2.4.jar的库。

8、编写AddPerson.java代码如下:

—————————————–

Person.Builder p = Person.newBuilder();

p.setId(1);

p.setName(“dna”);

……

p.build();



System.out.println(TextFormat.printToString(p.build()));



AddressBook.Builder addressBook = AddressBook.newBuilder();

addressBook.addPerson(p);



FileOutputStream output = new FileOutputStream(“test.file”);

addressBook.build().writeTo(output);

output.close();

—————————————–

输出是:(文本化内容)

—————————————–

name: “dna”

id: 1

—————————————–

输出文件test.file中的将是序列化过的内容

9、编写ListPerson.java代码如下:

—————————————–

AddressBook addressBook = AddressBook.parseFrom(new FileInputStream(“test.file”));



for (Person person: addressBook.getPersonList()) {

System.out.println(“Person ID: ” + person.getId());

……

—————————————–



总结适用protobuf的场合:
需要和其它系统做消息交换的,对消息大小很敏感的。
小数据的场合。如果你是大数据,用它并不适合。
跨平台、跨语言时。



参考:

http://code.google.com/intl/zh-CN/apis/protocolbuffers/docs/overview.html

http://rdc.taobao.com/team/jm/archives/389

原创粉丝点击