使用maven插件生成grpc所需要的Java代码

1、首先需要编写自己需要的.proto文件,本文重点不在这里,.proto可以参考grpc官方例子

https://grpc.io/docs/quickstart/java.html

2、创建自己的Java工程(只要是maven工程就行),把.proto文件放到src/main/proto目录下面

3、在项目的pom.xml中加入相关插件的配置内容,可以直接复制grpc官方的,实测很好用

https://github.com/grpc/grpc-java

<build>
  <extensions>
    <extension>
      <groupId>kr.motd.maven</groupId>
      <artifactId>os-maven-plugin</artifactId>
      <version>1.5.0.Final</version>
    </extension>
  </extensions>
  <plugins>
    <plugin>
      <groupId>org.xolstice.maven.plugins</groupId>
      <artifactId>protobuf-maven-plugin</artifactId>
      <version>0.5.1</version>
      <configuration>
        <protocArtifact>com.google.protobuf:protoc:3.5.1-1:exe:${os.detected.classifier}</protocArtifact>
        <pluginId>grpc-java</pluginId>
        <pluginArtifact>io.grpc:protoc-gen-grpc-java:1.17.1:exe:${os.detected.classifier}</pluginArtifact>
      </configuration>
      <executions>
        <execution>
          <goals>
            <goal>compile</goal>
            <goal>compile-custom</goal>
          </goals>
        </execution>
      </executions>
    </plugin>
  </plugins>
</build>

4、然后在IDE的maven面板上分别点击下面两个任务。点击protobuf:compile生成的5个文件是与protobuf序列化相关的,也就相当于是数据交换时的java bean。点击protobuf:compile-custom生成的1个文件是与grpc相关的,主要用于与服务端通信的。

5、自动生成的代码在target/generated-sources/protobuf里,可以移动到自己项目的相关目录下面。具体使用方法比较简单,可以参看官方的例子。

https://grpc.io/docs/quickstart/java.html

原文地址:https://www.cnblogs.com/kumu/p/10105744.html