大家好,欢迎来到这里。在项目中使用Netty进行通信协议数据序列化,使用protoBuf生成Java文件,在网上查询好多文章都没有相应的步骤去整理。像我这样第一次接触项目中新技术需要自己动手去处理的,这是我在项目中遇到并解决的方案,想和大家一起分享我的快乐!希望这篇文章能够帮助到你们,谢谢!
protoBuf 概念
转载地址: 序列化-ProtoBuf_51CTO博客_protobuf序列化
使用protoc-jar-maven-plugin 插件生成Java文件
1、导入Maven
<properties>
<protobuf.version>3.11.4</protobuf.version>
</properties>
使用protobuf-java
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>${protobuf.version}</version>
</dependency>
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java-util</artifactId>
<version>${protobuf.version}</version>
</dependency>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.6.7</version>
<configuration>
<executable>true</executable>
<layout>JAR</layout>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
<configuration>
<attach>false</attach>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>com.github.os72</groupId>
<artifactId>protoc-jar-maven-plugin</artifactId>
<version>3.11.4</version>
<executions>
<execution>
<phase>generate-sources</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<protocVersion>${protobuf.version}</protocVersion>
<inputDirectories>
<include>src/main/resources/proto</include>
</inputDirectories>
<outputTargets>
<outputTarget>
<type>java</type>
<outputDirectory>src/main/java</outputDirectory>
</outputTarget>
</outputTargets>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
2、项目结构
3、前期准备就绪、开始编译项目
4、将JSON数据转换成protoBuf生成的Java类
导入Maven库
<dependency>
<groupId>com.googlecode.protobuf-java-format</groupId>
<artifactId>protobuf-java-format</artifactId>
<version>1.4</version>
</dependency>
案例如下:
QueryProtocol.SendMessage.Builder builder = QueryProtocol.SendMessage.newBuilder();
InputStream value = new ByteArrayInputStream(msg.getBytes());
JsonFormat jsonFormat = new JsonFormat();
jsonFormat.merge(value, builder);
QueryProtocol.SendMessage sendMessage = builder.build();