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文件:
1 package tutorial; 2 3 option java_package = "com.protobuftest.protobuf"; 4 5 option java_outer_classname = "PersonProbuf"; 6 7 message Person { 8 9 required string name = 1; 10 11 required int32 id = 2; 12 13 optional string email = 3; 14 15 enum PhoneType { 16 17 MOBILE = 0; 18 19 HOME = 1; 20 21 WORK = 2; 22 23 } 24 25 message PhoneNumber { 26 27 required string number = 1; 28 29 optional PhoneType type = 2 [default = HOME]; 30 31 } 32 33 repeated PhoneNumber phone = 4; 34 35 message CountryInfo { 36 37 required string name = 1; 38 39 required string code = 2; 40 41 optional int32 number = 3; 42 43 } 44 45 } 46 47 message AddressBook { 48 49 repeated Person person = 1; 50 51 }
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);
}
}