Intellij IDEA中使用Protobuf的正確姿式

1、.proto文件語法高亮顯示

    須要安裝Protobuf Support插件java

   依次點擊Intellij中的「File」-->"Settings"-->"Plugins"-->"Browse repositories",以下所示:maven

輸入Protobuf,以下所示ide

安裝完後,重啓Intellij IDEA,查看.proto文件,會發現已經支持語法高亮顯示。ui

 

2、將.proto文件轉成Java類

    通常的作法,是執行protoc命令,依次將.proto文件轉成Java類:google

protoc.exe -I=d:/tmp --java_out=d:/tmp d:/tmp/monitor_data.proto

不過gRPC官方推薦了一種更優雅的使用姿式,能夠經過maven輕鬆搞定spa

 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類3d

  使用maven的編譯命令,便可在target中看到根據.proto文件生成的Java類,以下所示:netty

3、遇到的坑code

1.打開.proto文件後,顯示「File not found」提示,以下所示:

這種狀況,通常是未設置.proto文件所在文件夾爲源文件,能夠進行以下設置:

 在.proto文件所在的文件夾上右鍵,設置目錄爲源文件根目錄,以下所示:

相關文章
相關標籤/搜索