-
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:

里面的内容如下:
1.packageprotobuf;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的内如下:
4.在proto目录下新建.proto文件"person.proto",其中内容如下:01.packageorg.zhu.utils;02.03.publicclassGenerateClass {04./**05.* 调用protoc.exe生成java数据访问类06.* */07.publicstaticvoidmain(String[] args)throwsException {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.}01.packagetestProtobuf;//生成的数据访问类所在的包名(注意:在此无需写全包路径)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.enumPhoneType {//设置一个枚举类型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,内容如下:
01./**02.* 测试PersonProbuf.java03.* */04.publicclassTestPersonProbuf {05.06./**07.* @param args08.* @throws Exception09.*/10.publicstaticvoidmain(String[] args)throwsException {11.// 序列化过程12.// PersonProtobuf是生成的数据访问类的名字,即proto文件中的java_outer_classname13.// Person是里面某个消息序列的名字,即proto文件中的message Person14.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 =newByteArrayInputStream(buf);29.BufferedOutputStream bos =newBufferedOutputStream(newFileOutputStream("F:/protobuf.txt"));//设置输出路径30.BufferedInputStream bis =newBufferedInputStream(stream);31.intb = -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 =newBufferedInputStream(newFileInputStream("F:/protobuf.txt"));56.byteb2 = -1;57.List<Byte> list =newLinkedList<Byte>();58.while((b2 = (byte) bis2.read()) != -1) {59.list.add(b2);60.}61.bis2.close();62.intlength = list.size();63.byte[] byt =newbyte[length];64.for(inti =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除了占用空间小外,还有速度快,使用简单等诸多优点。
参考本示例工程代码http://www.it165.net/uploadfile/files/2014/0218/protobuf.zip
更详尽的使用说明请参看官方文档;https://developers.google.com/protocol-buffers/docs/javatutorial