目前,在网络通信和通用数据交换等应用场景中经常使用的技术是 JSON 或 XML,而在最近的开发中接触到了 Google 的 ProtoBuf。ProtoBuf是Google开源的一种数据传输协议,类似于XML、JSON等技术,优点是ProtoBuf序列化和反序列化的性能非常好,灵活,高效,自动,跨平台,跨语言,最主要的是它的代码生成机制。只要写一个.proto数据文件,再用编译器编译一下,可以编译成对应语言的代码。
protocol buffers 是一种语言无关、平台无关、可扩展的序列化结构数据的方法,它可用于(数据)通信协议、数据存储等。ProtoBuf 是结构数据序列化方法,序列化:将结构数据或对象转换成能够被存储和传输(例如网络传输)的格式,同时应当要保证这个序列化结果在之后(可能在另一个计算环境中)能够被重建回原来的结构数据或对象。
* XML、JSON、ProtoBuf 都具有数据结构化和数据序列化的能力
* XML、JSON 更注重数据结构化,关注人类可读性和语义表达能力。ProtoBuf 更注重数据序列化,关注效率、空间、速度,人类可读性差,语义表达能力不足(为保证极致的效率,会舍弃一部分元信息)
* ProtoBuf 的应用场景更为明确,XML、JSON 的应用场景更为丰富。
在Java中使用protobuf需要jar包,下载protobuf-Java-***.jar包文件,添加到项目中即可,实例如下:
pom.xml文件
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<protobuf.version>3.3.0</protobuf.version>
<grpc.version>1.6.1</grpc.version>
</properties>
<dependencies>
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>${protobuf.version}</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-netty</artifactId>
<version>${grpc.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-protobuf</artifactId>
<version>${grpc.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-stub</artifactId>
<version>${grpc.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<extensions>
<extension>
<groupId>kr.motd.maven</groupId>
<artifactId>os-maven-plugin</artifactId>
<version>1.5.0.Final</version>
</extension>
</extensions>
<plugins>
<plugin>
<groupId>org.xolstice.maven.plugins</groupId>
<artifactId>protobuf-maven-plugin</artifactId>
<version>0.5.0</version>
<configuration>
<protocArtifact>com.google.protobuf:protoc:${protobuf.version}:exe:${os.detected.classifier}
</protocArtifact>
<pluginId>grpc-java</pluginId>
<pluginArtifact>io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier}
</pluginArtifact>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>compile-custom</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
***.proto文件
syntax = "proto2";
//package com;
option java_package = "com.protobuf";
option java_outer_classname = "Model";
message Student {
required int64 id = 1;
required int32 age = 2;
required string name = 3;
}
在maven 的projects视图中选择 protobuf:compile命令执行即可生成对应的类文件。(注意proto文件夹存放在main文件夹下)
public class Test {
public static void main(String[] args) {
// 序列化
Model.Student.Builder builder = Model.Student.newBuilder();
builder.setId(1L).setName("2").setAge(3);
Model.Student student = builder.build();
System.out.println(student.toString());
// 反序列化
byte[] bytes = student.toByteArray();
System.out.println(bytes);
try {
Model.Student d = Model.Student.parseFrom(bytes);
System.out.println(d.toString());
} catch (InvalidProtocolBufferException e) {
e.printStackTrace();
}
}
}
结果:
id: 1
age: 3
name: "2"