一、.proto文件語法高亮顯示
需要安裝Protobuf Support插件
依次點擊Intellij中的“File”-->"Settings"-->"Plugins"-->"Browse repositories",如下所示:
輸入Protobuf,如下所示
安裝完后,重啟Intellij IDEA,查看.proto文件,會發現已經支持語法高亮顯示。
二、將.proto文件轉成Java類
一般的做法,是執行protoc命令,依次將.proto文件轉成Java類:
protoc.exe -I=d:/tmp --java_out=d:/tmp d:/tmp/monitor_data.proto
不過gRPC官方推薦了一種更優雅的使用姿勢,可以通過maven輕松搞定
2.1 pom.xml文件配置
<properties>
<grpc.version>1.6.1</grpc.version>
<protobuf.version>3.3.0</protobuf.version>
</properties>
<dependencies> <dependency> <groupId>io.grpc</groupId> <artifactId>grpc-netty</artifactId> <version>${grpc.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>io.grpc</groupId> <artifactId>grpc-protobuf</artifactId> <version>${grpc.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>io.grpc</groupId> <artifactId>grpc-stub</artifactId> <version>${grpc.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>com.google.protobuf</groupId> <artifactId>protobuf-java</artifactId> <version>${protobuf.version}</version> </dependency> </dependencies>
<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.0</version> <configuration> <protocArtifact>com.google.protobuf:protoc:${protobuf.version}:exe:${os.detected.classifier}</protocArtifact> <pluginId>grpc-java</pluginId> <pluginArtifact>io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier}</pluginArtifact> </configuration> <executions> <execution> <goals> <goal>compile</goal> <goal>compile-custom</goal> </goals> </execution> </executions> </plugin> </plugins> </build>
2.2 編譯生成Java類
使用maven的編譯命令,即可在target中看到根據.proto文件生成的Java類,如下所示:
三、遇到的坑
1.打開.proto文件后,顯示“File not found”提示,如下所示:
這種情況,一般是未設置.proto文件所在文件夾為源文件,可以進行如下設置:
在.proto文件所在的文件夾上右鍵,設置目錄為源文件根目錄,如下所示:
參考文檔:
https://github.com/google/protobuf
https://github.com/protostuff/protobuf-jetbrains-plugin
https://github.com/grpc/grpc-java