您的位置:首页 > 其它

protobuf简介

2017-03-05 13:00 162 查看

简介

protobuf是google开源的一个数据序列化与反序列化工具,由于其支持多种语言、各种平台,多被用于对象的存储,远程调用等方向。

用户首先定义对象的结构,根据结构生成对应语言的源码,然后就可以在各种语言中使用protobuf将数据进行序列化和反序列化。

使用

下面是一个简单的使用的例子:

首先需要定义一个.proto文件,其中需要定义你希望操作的对象的结构。

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;
}

保存为person.proto文件,之后下载protoc编译工具,并解压,使用protoc将proto文件生成java类。

protoc.exe --java_out=. person.proto

在指定的java_out目录下就可以生成java对应的类,这里生成了PersonOuterClass.java。将文件放入项目,并引入protobuf的jar包。

compile group: 'com.google.protobuf', name: 'protobuf-java', version: '3.1.0'

接下来就可以使用protobuf进行对象的操作了。

public static void main(String[] args) throws Exception{
//创建对象
PersonOuterClass.Person p= PersonOuterClass.Person.newBuilder().setName("my_name").setId(2).build();
System.out.print(p.toString());
//序列化对象
FileOutputStream fos=new FileOutputStream("D://person");
p.writeTo(fos);
fos.close();
//反序列化对象
FileInputStream fis=new FileInputStream("D://person");
PersonOuterClass.Person pread=PersonOuterClass.Person.parseFrom(fis);
System.out.println(pread.toString());
fis.close();
}

优势

与java原生的serializable接口进行比较。

public class JavaPerson implements Serializable{
public String name;
public Integer id;
public String email;

public enum PhoneType{
MOBILE,HOME,WORK
}
public class PhoneNumber{
public String number;
public PhoneType type;
}
List<PhoneNumber> phone;

public static void main(String[] args) throws Exception{
JavaPerson jp=new JavaPerson();
jp.name="my_name";
jp.id=2;

FileOutputStream fileOut = new FileOutputStream("d://person.ser");
ObjectOutputStream outStream = new ObjectOutputStream(fileOut);
outStream.writeObject(jp);
outStream.close();
fileOut.close();

FileInputStream fileIn =new FileInputStream("d://person.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
jp = (JavaPerson) in.readObject();
in.close();
fileIn.close();
}
}

运行比较下来:



protobuf较java默认形式代码更简洁。

循环运行10000次序列化和反序列化后protobuf比java快约30%。

生成的文件protobuf有11字节而java有215字节。

protobuf提供额外的字段校验支持。


目录

proto2语法

proto3语法

protobuf编码

protobuf自解释message

java操作protobuf

使用gradle生成protobuf
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: