Java protobuf框架使用向导

时间:2022-09-01 05:04:31

ProtoBuf,全称是Protocol Buffers, 它是谷歌内部用的一种高效的、可扩展的对结构化数据进行编码的格式规范。谷歌自己内部很多程序之间的通信协议都用了ProtoBuf。

下面介绍的是使用Java ProtoBuf的基本步骤:

1.http://code.google.com/p/protobuf/downloads/list ,选择其中的win版本下载

2.下载一个protobuf-java-2.4.1.jar文件(注意,要与你刚才下的proto.exe版本相同,否则可能出现编译通不过现象)

http://grepcode.com/snapshot/repo1.maven.org/maven2/com.google.protobuf/protobuf-java/2.4.1

3.在proto.exe同级目录,编写一个msg.proto文件:

 package tutorial; 

 option java_package = "com.protobuftest.protobuf"; 

 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; 

   message CountryInfo {

           required string name = 1;

           required string code = 2;

           optional int32 number = 3;

   }

 } 

 message AddressBook { 

   repeated Person person = 1; 

 } 

4.使用如下命令编译这个文件:

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

5.将生成的ProtoBufferPractice.java文件引入eclipse

6.把下载的protobuf-java-2.4.1.jar也引入工程

7.使用方法:

package com.protobuftest;

import java.util.List;

import com.google.protobuf.InvalidProtocolBufferException;

import com.protobuftest.protobuf.PersonProbuf;

import com.protobuftest.protobuf.PersonProbuf.Person;

import com.protobuftest.protobuf.PersonProbuf.Person.PhoneNumber;

import com.protobuftest.protobuf.PersonProbuf.Person.PhoneNumberOrBuilder;

import com.protobuftest.protobuf.PersonProbuf.Person.PhoneType;

public class ProtoBufTest {

/**

* @param args

*/

public static void main(String[] args) {

// TODO Auto-generated method stub

PersonProbuf.Person.Builder builder = PersonProbuf.Person.newBuilder();

builder.setEmail("kkk@email.com");

builder.setId(1);

builder.setName("TestName");

builder.addPhone(PersonProbuf.Person.PhoneNumber.newBuilder().setNumber("131111111").setType(PersonProbuf.Person.PhoneType.MOBILE));

builder.addPhone(PersonProbuf.Person.PhoneNumber.newBuilder().setNumber("011111").setType(PersonProbuf.Person.PhoneType.HOME));

Person person = builder.build();

byte[] buf = person.toByteArray();

try {

Person person2 = PersonProbuf.Person.parseFrom(buf);

System.out.println(person2.getName() + ", " + person2.getEmail());

List<PhoneNumber> lstPhones = person2.getPhoneList();

for (PhoneNumber phoneNumber : lstPhones) {

System.out.println(phoneNumber.getNumber());

}

} catch (InvalidProtocolBufferException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

System.out.println(buf);

}

}

源文档 <http://blog.csdn.net/csharp25/article/details/6632127>