1. 先容Protocol Buffers
Protocal Buffers(简称protobuf)是谷歌的一项技能,用于布局化的数据序列化、反序列化,昆山软件开发,常用于RPC 系统(Remote Procedure Call Protocol System)和一连数据存储系统。
其雷同于XML生成息争析,但protobuf的效率高于XML,不外protobuf生成的是字节码,昆山软件开发,可读性比XML差,昆山软件开发,雷同的尚有json、Java的Serializable等。
很适合做数据存储或 RPC 数据互换名目。可用于通讯协议、数据存储等规模的语言无关、平台无关、可扩展的序列化布局数据名目。
2. Idea 安装protobuf插件
安装插件protobuf Support,之后重启
昆山软件开拓 ffers Protocal Buffers(简称protobuf)是谷歌的一项技能" src="http://www.importnew.com/https:/images2018.cnblogs.com/blog/408927/201805/408927-20180511003443289-1489480098.png" width="870" height="415" />
3. 设置依赖
pom.xml添加
<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>
4. 书写proto文件
syntax = "proto3"; option java_package = "com.jihite"; option java_outer_classname = "PersonModel"; message Person { int32 id = 1; string name = 2; string email = 3; }
5. 转化成Java文件
昆山软件开拓 ffers Protocal Buffers(简称protobuf)是谷歌的一项技能" src="http://www.importnew.com/https:/images2018.cnblogs.com/blog/408927/201805/408927-20180511170617720-917235301.png" width="986" height="459" />
6. 测试
把生成的类考的代码路径下,用下面测试用例测试
package com.jihite; import com.google.protobuf.InvalidProtocolBufferException; import org.junit.Test; public class protobufTest { @Test public void testN() throws InvalidProtocolBufferException { PersonModel.Person.Builder builder = PersonModel.Person.newBuilder(); builder.setId(1); builder.setName("jihite"); builder.setEmail("jihite@jihite.com"); PersonModel.Person person = builder.build(); System.out.println("before:" + person); System.out.println("===Person Byte:"); for (byte b : person.toByteArray()) { System.out.print(b); } System.out.println("================"); byte[] byteArray = person.toByteArray(); PersonModel.Person p2 = PersonModel.Person.parseFrom(byteArray); System.out.println("after id:" + p2.getId()); System.out.println("after name:" + p2.getName()); System.out.println("after email:" + p2.getEmail()); } }
功效
before:id: 1 name: "jihite" email: "jihite@jihite.com" ===Person Byte: 811861061051041051161012617106105104105116101641061051041051161014699111109================ after id:1 after name:jihite after email:jihite@jihite.com