protobuf 3初体验
背景
记录一下从proto文件生成java类的过程
使用maven工具生成
参考自官方文档[2]
proto3文件准备
sample.proto
,内容如下:
syntax = "proto3";
package sample;
message Audio {
bytes data = 1;
}
message Embedding {
bytes data = 1;
}
增加运行时pom
protobuf-java的版本,和protoc的版本要保持一致。
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>3.19.2</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-netty-shaded</artifactId>
<version>1.44.0</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-protobuf</artifactId>
<version>1.44.0</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-stub</artifactId>
<version>1.44.0</version>
</dependency>
<dependency> <!-- necessary for Java 9+ -->
<groupId>org.apache.tomcat</groupId>
<artifactId>annotations-api</artifactId>
<version>6.0.53</version>
<scope>provided</scope>
</dependency>
增加生成代码的插件
<build>
<extensions>
<extension>
<groupId>kr.motd.maven</groupId>
<artifactId>os-maven-plugin</artifactId>
<version>1.6.2</version>
</extension>
</extensions>
<plugins>
<plugin>
<groupId>org.xolstice.maven.plugins</groupId>
<artifactId>protobuf-maven-plugin</artifactId>
<version>0.6.1</version>
<configuration>
<protocArtifact>com.google.protobuf:protoc:3.19.2:exe:${os.detected.classifier}</protocArtifact>
<pluginId>grpc-java</pluginId>
<pluginArtifact>io.grpc:protoc-gen-grpc-java:1.44.0:exe:${os.detected.classifier}</pluginArtifact>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>compile-custom</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
生成
将proto文件放在src/main/proto目录下,运行maven compile即可生成对应的类。
使用cli工具生成
环境准备
环境:windows + java
安装包:
- https://github.com/protocolbuffers/protobuf/releases下面的
protoc-3.19.4-win64.zip
- https://repo1.maven.org/maven2/io/grpc/protoc-gen-grpc-java/1.44.0/protoc-gen-grpc-java-1.44.0-windows-x86_64.exe:改名为protoc-gen-grpc-java.exe,放在PATH下。
或者直接下载二进制包:
wget https://repo1.maven.org/maven2/io/grpc/protoc-gen-grpc-java/1.30.2/protoc-gen-grpc-java-1.30.2-osx-x86_64.exe
proto3文件准备
sample.proto
,内容如下:
syntax = "proto3";
package sample;
message Audio {
bytes data = 1;
}
message Embedding {
bytes data = 1;
}
编译
生成序列化java类,即只翻译message段[1]:
protoc --java_out=. sample.proto
生成对应的Service
protoc --plugin=protoc-gen-grpc-java --grpc-java_out=. voiceprint.proto
两个都需要执行,请依次执行。