1.protobuf簡介java
Protobuf是一個靈活的、高效的用於序列化數據的協議。相比較XML和JSON格式,protobuf更小、更快、更便捷。Protobuf是跨語言的,而且自帶了一個編譯器(protoc),只須要用它進行編譯,能夠編譯成Java、python、C++等代碼,而後就能夠直接使用,不須要再寫其餘代碼,自帶有解析的代碼。一條消息數據,用protobuf序列化後的大小是json的10分之一,xml格式的20分之一,是二進制序列化的10分之一。python
2.安裝插件json
在idea裏安裝插件Protobuf Supportmaven
3.配置ide
<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> <dependency> <groupId>com.google.protobuf</groupId> <artifactId>protobuf-java</artifactId> <version>${protobuf.version}</version> </dependency>
<extensions> <extension> <groupId>kr.motd.maven</groupId> <artifactId>os-maven-plugin</artifactId> <version>1.5.0.Final</version> </extension> </extensions>
<!--protobuf插件-->
<plugin>
<groupId>org.xolstice.maven.plugins</groupId>
<artifactId>protobuf-maven-plugin</artifactId>
<version>0.5.1</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>
4.建立proto文件測試
syntax = "proto3"; option java_package = "com.ynt.ai.activemq.protobuf"; option java_outer_classname = "PersonModel"; message Person { int32 id = 1; string name = 2; string email = 3; }
5.生成java對象文件ui
經過Protobuf插件的compile命令,以下圖所示,自動生成對象文件。google
6.測試idea
PersonMsg.Person person = PersonMsg.Person.newBuilder().setId(2).setName("test") .setEmail("test@163.com").build(); byte[] results = person.toByteArray(); for (byte b : results) { log.info(String.valueOf(b)); }