Google 的开源技术protobuf 简介与例子

来源:互联网 发布:mac上的翻墙工具 编辑:程序博客网 时间:2024/05/17 15:18

本文主要偏向于介绍怎么使用Google的Protocol Buffer技术来压缩与解析你的数据文件,更加详细的信息请参阅Google开放的开发者网页文档,地址为:http://code.google.com/apis/protocolbuffers/docs/overview.html 。

     一、简单的介绍

     当然,在继续本文之前,读者还是需要对Google Protocol Buffers有一些基本的认识。Protocol buffers是一个用来序列化结构化数据的技术,支持多种语言诸如C++、Java以及Python语言,可以使用该技术来持久化数据或者序列化成网络传输的数据。相比较一些其他的XML技术而言,该技术的一个明显特点就是更加节省空间(以二进制流存储)、速度更快以及更加灵活。

     通常,编写一个protocol buffers应用需要经历如下三步:

     1、定义消息格式文件,最好以proto作为后缀名

     2、使用Google提供的protocol buffers编译器来生成代码文件,一般为.h和.cc文件,主要是对消息格式以特定的语言方式描述

     3、使用protocol buffers库提供的API来编写应用程序  

 

     二、定义Proto文件 

     proto文件即消息协议原型定义文件,在该文件中我们可以通过使用描述性语言,来良好的定义我们程序中需要用到数据格式。首先我们可以通过Google在线文档上提供的一个电话簿的例子来了解下,不过稍微加了点改动。     

复制代码
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;
  
  required bytes  unsure = 5;      
//Add byte array here    
}

message AddressBook {
  repeated Person person 
= 1;
}
复制代码

     诚如你看到的一样,消息格式定义很简单,对于每个字段而言都有一个修饰符(required/repeated/optional)、字段类型(bool/string/bytes/int32等)和字段标签(Tag)组成。

     三个修饰符从词义上可以很清楚的弄明白,

    1)对于required的字段而言,初值是必须要提供的,否则字段的便是未初始化的。在Debug模式的buffer库下编译的话,序列化话的时候可能会失败,而且在反序列化的时候对于该字段的解析会总是失败的。所以,对于修饰符为required的字段,请在序列化的时候务必给予初始化。

    2)对于optional的字段而言,如果未进行初始化,那么一个默认值将赋予该字段,当然也可以指定默认值,如上述proto定义中的PhoneType字段类型。

    3)对于repeated的字段而言,该字段可以重复多个,google提供的这个addressbook例子便有个很好的该修饰符的应用场景,即每个人可能有多个电话号码。在高级语言里面,我们可以通过数组来实现,而在proto定义文件中可以使用repeated来修饰,从而达到相同目的。当然,出现0次也是包含在内的。      

    其中字段标签标示了字段在二进制流中存放的位置,这个是必须的,而且序列化与反序列化的时候相同的字段的Tag值必须对应,否则反序列化会出现意想不到的问题。


二、示例Demo

protocol buffers的使用示例

如果不了解protocol buffers,可以先参看:http://blog.csdn.net/zhu_xun/article/details/19343079

本例的protobuf的版本为2.5.0,运行环境为windows平台(当然,在Linux下使用的方法也一样,只不过是使用shell脚本驱动protobuf程序的运行)

下载protobuf运行环境包:可以到http://download.csdn.net/detail/u012875880/6931679下载。

一、测试protobuf:

1.先写个例子测试一下吧:

在proto.exe所在的目录下新建一个.proto文件test.proto:

\

里面的内容如下:

 

view sourceprint?
1.package protobuf;
2.option java_package = "protobuf";
3.option java_outer_classname = "FirstExample";
4.message testBuf  {
5.required string name= 1;
6.required int32 age = 2;
7.}

 

 

2.打开dos命令窗口

3.进入protocbuf目录,本例中目录为C:UserszhkjDesktopprotoc-2.5.0-win32

cd C:UserszhkjDesktopprotoc-2.5.0-win32

4.运行protoc.exe程序生成数据访问类:

protoc.exe --java_out=./ ./test.proto

\

说明:java_out后的第一参数表示生成的数据访问类所在的目录,本例中为当前目录;第二个为proto文件的位置,本例中为当前目录下的test.proto文件。

运行上述命令后,会发现在当前目录下生成了一个文件夹"protobuf":

\

这是,进入刚生成的protobuf文件夹,会发现有个Java类:FirstExample.java

至此,一个简单的测试就ok了。

二、在eclipse工程中的使用说明

1.新建一个Java工程"protobuf",工程目录结构如下:

\

2.在lib目录下导入protobuf-java-2.5.0.jar、将protoc.exe拷贝至在protobuf工程跟目录下。

3.在org.zhu.utils工具包里面新建一个可以自动生成数据访问类的工具类"GenerateClass.java",GenerateClass的内如下:

 

view sourceprint?
01.package org.zhu.utils;
02. 
03.public class GenerateClass {
04./**
05.* 调用protoc.exe生成java数据访问类
06.* */
07.public static void main(String[] args) throws Exception {
08.String protoFile = "testFirstExample.proto";//如果要更换生成的数据访问类,只需在此进行更改
09.//String protoFile = "person.proto";
10.String strCmd = "protoc.exe --java_out=./src ./proto/" + protoFile;
11.Runtime.getRuntime().exec("cmd /c " + strCmd).waitFor();//通过执行cmd命令调用protoc.exe程序
12. 
13.}
14.}
4.在proto目录下新建.proto文件"person.proto",其中内容如下:

 

 

view sourceprint?
01.package testProtobuf;//生成的数据访问类所在的包名(注意:在此无需写全包路径)
02.option java_package = "org.zhu.testProtobuf";//生成的数据访问类所在包的全路径
03.option java_outer_classname = "PersonProbuf";//生成的数据访问类的类名
04.message Person {
05.required string name = 1;//必须字段,在后面的使用中必须为该段设置值
06.required int32 id = 2;//同上
07.optional string email = 3;//可选字段,在后面的使用中可以自由决定是否为该字段设置值
08. 
09.enum PhoneType {//设置一个枚举类型
10.MOBILE = 0;
11.HOME = 1;
12.WORK = 2;
13.}
14. 
15.message PhoneNumber {
16.required string number = 1;
17.optional PhoneType type = 2 [default = HOME];
18.}
19. 
20.repeated PhoneNumber phone = 4;//重复字段(可以认为是一个集合),在后面的使用中可以为该字段设置多个值
21.}

 

注:以上字段后面的"0","1","2"数字表示该条消息序列化时的字段编号即顺序

5.运行GenerateClass.java程序生成数据访问类Person.java

运行程序后,需刷新protobuf工程,这是你可以发现,在org,zhu,testProtobuf包下生成了一个PersonProtobuf.java类,参考如下:

\

6.编写测试类:

在org.zhu.test包下新建测试类TestPersonProbuf.java,内容如下:

 

view sourceprint?
01./**
02.* 测试PersonProbuf.java
03.* */
04.public class TestPersonProbuf {
05. 
06./**
07.* @param args
08.* @throws Exception
09.*/
10.public static void main(String[] args) throws Exception {
11.// 序列化过程
12.// PersonProtobuf是生成的数据访问类的名字,即proto文件中的java_outer_classname
13.// Person是里面某个消息序列的名字,即proto文件中的message Person
14.PersonProtobuf.Person.Builder builder = PersonProtobuf.Person.newBuilder();
15.//设置消息序列中的字段值
16.builder.setEmail("zhuxun777@gmail.com");
17.builder.setId(320324);
18.builder.setName("Jack Zhu");
19.//phone字段在person.proto文件中被定义为repeated型,可以放多个值
20.//(在本例中,phone字段的数据类型为消息类型PhoneNumber)
21.builder.addPhone(PersonProtobuf.Person.PhoneNumber.newBuilder().setNumber("18762678793").setType(Person.PhoneType.HOME));
22.builder.addPhone(PersonProtobuf.Person.PhoneNumber.newBuilder().setNumber("18651581021").setType(Person.PhoneType.HOME));
23. 
24.Person person = builder.build();
25.byte[] buf = person.toByteArray();
26. 
27.//把序列化后的数据写入本地磁盘
28.ByteArrayInputStream stream = new ByteArrayInputStream(buf);
29.BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("F:/protobuf.txt"));//设置输出路径
30.BufferedInputStream bis = new BufferedInputStream(stream);
31.int b = -1;
32.while ((b = bis.read()) != -1) {
33.bos.write(b);
34.}
35.bis.close();
36.bos.close();
37. 
38. 
39.//读取序列化后的数据
40.try {
41.Person person01 = PersonProtobuf.Person.parseFrom(buf);
42.List<PhoneNumber> phones = person01.getPhoneList();
43.String strPhone = "";
44.for(PhoneNumber phone : phones){
45.strPhone += phone.getNumber() + "   ";
46.}
47.//String strResult = person01.getName() + "," + person01.getId() + "," + person01.getEmail() + "," + strPhone;
48.//System.out.println(strResult);
49.catch (InvalidProtocolBufferException e) {
50.e.printStackTrace();
51.}
52. 
53.//读取序列化后写入磁盘的数据
54.try {
55.BufferedInputStream bis2 = new BufferedInputStream(new FileInputStream("F:/protobuf.txt"));
56.byte b2 = -1;
57.List<Byte> list = new LinkedList<Byte>();
58.while ((b2 = (byte) bis2.read()) != -1) {
59.list.add(b2);
60.}
61.bis2.close();
62.int length = list.size();
63.byte[] byt = new byte[length];
64.for(int i = 0; i < length; i++){
65.byt[i] = list.get(i);
66.}
67.Person person01 = PersonProtobuf.Person.parseFrom(byt);
68.List<PhoneNumber> phones = person01.getPhoneList();
69.String strPhone = "";
70.for(PhoneNumber phone : phones){
71.strPhone += phone.getNumber() + "   ";
72.}
73.String strResult = person01.getName() + "," + person01.getId() + "," + person01.getEmail() + "," + strPhone;
74.System.out.println(strResult);
75.catch (InvalidProtocolBufferException e) {
76.e.printStackTrace();
77.}
78.}
79. 
80.}

以上演示了把信息通过protobuf序列化后写入磁盘,以及从磁盘读取后反序列化的过程。protobuf把信息写入磁盘后,文件的大小为69字节,而用json表示大概有90多字节,用xml表示大概需150字节(在去掉xml换行及空格的情况下),用此可见protobuf的威力了。当然,protobuf除了占用空间小外,还有速度快,使用简单等诸多优点。

 

更详尽的使用说明请参看官方文档;https://developers.google.com/protocol-buffers/docs/javatutorial



本文为对以下文章的加工总结

http://www.cnblogs.com/royenhome/archive/2010/10/29/1864860.html

http://www.it165.net/pro/html/201402/9349.html

0 0