protobuf 3初体验

  |   0 评论   |   0 浏览

背景

记录一下从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

安装包:

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

生成

protoc --plugin=protoc-gen-grpc-java --grpc-java_out=. voiceprint.proto

参考

  1. Proto3.0 使用(java版)
  2. grpc-java@github