Protocol Buffers
Protocal Buffers(简称protobuf)是谷歌的一项技术,用于结构化的数据序列化、反序列化,常用于RPC 系统(Remote Procedure Call Protocol System)和持续数据存储系统。
其类似于XML生成和解析,但protobuf的效率高于XML,不过protobuf生成的是字节码,可读性比XML差,类似的还有json、Java的Serializable等。
很适合做数据存储或 RPC 数据交换格式。可用于通讯协议、数据存储等领域的语言无关、平台无关、可扩展的序列化结构数据格式。
Idea安装protobuf插件
配置依赖
pom.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| <dependencies> <dependency> <groupId>com.google.protobuf</groupId> <artifactId>protobuf-java</artifactId> <version>3.4.0</version> </dependency> </dependencies>
<build> <extensions> <extension> <groupId>kr.motd.maven</groupId> <artifactId>os-maven-plugin</artifactId> <version>1.4.1.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:3.1.0:exe:${os.detected.classifier} </protocArtifact> <pluginId>grpc-java</pluginId> </configuration> <executions> <execution> <goals> <goal>compile</goal> <goal>compile-custom</goal> </goals> </execution> </executions> </plugin> </plugins> </build>
|
书写proto文件
1 2 3 4 5 6 7
| syntax = "proto3" option java_package = "cn.joinhealth" option java_outer_classname = "LicenseModel"
message License { string permission = 1 }
|
转化成Java文件
测试
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| package cn.joinhealth.interview.web.root;
import com.google.protobuf.InvalidProtocolBufferException;
public class Test {
public static void main(String[] args) throws InvalidProtocolBufferException { LicenseModel.License.Builder builder = LicenseModel.License.newBuilder(); builder.setPermission("1,2,3,4,5,6,7,8,9,10");
LicenseModel.License license = builder.build(); System.out.println("before:" + license);
System.out.println("===Person Byte:"); for (byte b : license.toByteArray()) { System.out.print(b); } System.out.println(); System.out.println("================\n");
byte[] byteArray = license.toByteArray(); LicenseModel.License license1 = LicenseModel.License.parseFrom(byteArray); System.out.println("after:" + license1.getPermission()); } }
|
结果
1 2 3 4 5 6 7
| before:permission: "1,2,3,4,5,6,7,8,9,10"
===Person Byte: 10204944504451445244534454445544564457444948 ================
after:1,2,3,4,5,6,7,8,9,10
|