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