protocol buffers的使用示例

来源:互联网 发布:电脑软件怎么付费 编辑:程序博客网 时间:2024/05/22 09:59

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:


里面的内容如下:

package protobuf;option java_package = "protobuf";option java_outer_classname = "FirstExample";message testBuf  {  required string name= 1;  required int32 age = 2;}

2.打开dos命令窗口

3.进入protocbuf目录,本例中目录为C:\Users\zhkj\Desktop\protoc-2.5.0-win32

cd C:\Users\zhkj\Desktop\protoc-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的内如下:

public class GenerateClass_Windows {/** * Windows版本 * 调用protoc.exe生成java数据访问类 * */public static void main(String[] args) throws Exception {//String protoFile = "testFirstExample.proto";//如果要更换生成的数据访问类,只需在此进行更改String protoFile = "person.proto";////String strCmd = "protoc.exe --java_out=./src ./proto/" + protoFile;/** * protoc --java_out=./src--proto_path=./conf/person.proto可以简写为: * protoc --java_out=./src (空格)./conf/person.proto(把"proto_path"参数名去掉) * */String strCmd = "protoc.exe --java_out=./src--proto_path=./proto/" + protoFile;Runtime.getRuntime().exec("cmd /c " + strCmd).waitFor();//通过执行cmd命令调用protoc.exe程序}}


4.在proto目录下新建.proto文件"person.proto",其中内容如下:

package testProtobuf;//生成的数据访问类所在的包名(注意:在此无需写全包路径)option java_package = "org.zhu.testProtobuf";//生成的数据访问类所在包的全路径option java_outer_classname = "PersonProbuf";//生成的数据访问类的类名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;//重复字段(可以认为是一个集合),在后面的使用中可以为该字段设置多个值}

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


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

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


6.编写测试类:

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

/** * 测试PersonProbuf.java * */public class TestPersonProbuf {/** * @param args * @throws Exception  */public static void main(String[] args) throws Exception {// 序列化过程// PersonProtobuf是生成的数据访问类的名字,即proto文件中的java_outer_classname// Person是里面某个消息序列的名字,即proto文件中的message PersonPersonProtobuf.Person.Builder builder = PersonProtobuf.Person.newBuilder();//设置消息序列中的字段值builder.setEmail("zhuxun777@gmail.com");builder.setId(320324);builder.setName("Jack Zhu");//phone字段在person.proto文件中被定义为repeated型,可以放多个值//(在本例中,phone字段的数据类型为消息类型PhoneNumber)builder.addPhone(PersonProtobuf.Person.PhoneNumber.newBuilder().setNumber("18762678793").setType(Person.PhoneType.HOME));builder.addPhone(PersonProtobuf.Person.PhoneNumber.newBuilder().setNumber("18651581021").setType(Person.PhoneType.HOME));Person person = builder.build();byte[] buf = person.toByteArray();//把序列化后的数据写入本地磁盘ByteArrayInputStream stream = new ByteArrayInputStream(buf);BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("F:/protobuf.txt"));//设置输出路径BufferedInputStream bis = new BufferedInputStream(stream);int b = -1;while ((b = bis.read()) != -1) {bos.write(b);}bis.close();bos.close();//读取序列化后的数据try {Person person01 = PersonProtobuf.Person.parseFrom(buf);List<PhoneNumber> phones = person01.getPhoneList();String strPhone = "";for(PhoneNumber phone : phones){strPhone += phone.getNumber() + "   ";}//String strResult = person01.getName() + "," + person01.getId() + "," + person01.getEmail() + "," + strPhone;//System.out.println(strResult);} catch (InvalidProtocolBufferException e) {e.printStackTrace();}//读取序列化后写入磁盘的数据try {BufferedInputStream bis2 = new BufferedInputStream(new FileInputStream("F:/protobuf.txt"));byte b2 = -1;List<Byte> list = new LinkedList<Byte>();while ((b2 = (byte) bis2.read()) != -1) {list.add(b2);}bis2.close();int length = list.size();byte[] byt = new byte[length];for(int i = 0; i < length; i++){byt[i] = list.get(i);}Person person01 = PersonProtobuf.Person.parseFrom(byt);List<PhoneNumber> phones = person01.getPhoneList();String strPhone = "";for(PhoneNumber phone : phones){strPhone += phone.getNumber() + "   ";}String strResult = person01.getName() + "," + person01.getId() + "," + person01.getEmail() + "," + strPhone;System.out.println(strResult);} catch (InvalidProtocolBufferException e) {e.printStackTrace();}}}

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

如要参考本示例工程代码,可以到http://download.csdn.net/detail/u012875880/6933021下载

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





4 0
原创粉丝点击