IDEA + Maven + Protobuf 配置和使用

最近學習NIO學到了netty,繼而瞭解到了個神奇的東東protobuf,這個是幹什麼的我就不在此贅述了,這篇博文的主要目的是記錄和分享protobuf配合idea以及maven的使用

安裝protoc

首先我們需要下載protobuf,github下載地址
protobuf下載
根據自己電腦的情況下載相應的包,然後解壓到一定的位置。
我使用的64位win10,需要配置環境變量,在path中添加(配置後可以直接在cmd中使用命令)
protobuf配置環境變量

IDEA中的配置

首先安裝插件,File >> settings >> plugins,搜索protobuf,安裝Protobuf Support

maven配置

在pom.xml中添加jar包引用:

<dependency>
   <groupId>com.google.protobuf</groupId>
   <artifactId>protobuf-java</artifactId>
   <version>3.9.0</version>
</dependency>

添加porotbuf編譯插件

<plugin>
                <groupId>org.xolstice.maven.plugins</groupId>
                <artifactId>protobuf-maven-plugin</artifactId>
                <version>0.6.1</version>
                <configuration>
                    <protocExecutable>
                        D:\Java\protoc-3.9.1-win64\bin\protoc.exe  <!-- 剛剛環境變量配置的位置 -->
                    </protocExecutable>
                    <pluginId>protoc-java</pluginId>
                    <!-- proto文件放置的目錄 -->
                    <protoSourceRoot>${project.basedir}/src/main/java/com/luxy/netty/proto</protoSourceRoot>
                    <!-- 生成文件的目錄 -->
                    <outputDirectory>${project.basedir}/src/main/java</outputDirectory>
                    <!-- 生成文件前是否把目標目錄清空,這個最好設置爲false,以免誤刪項目文件 -->
                    <clearOutputDirectory>false</clearOutputDirectory>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
測試

在項目的src/main/java/com/luxy/netty/proto目錄下創建user.proto

syntax = "proto3";
package com.luxy.netty.proto;
option java_outer_classname="UserProto";
message User {
    string name = 1;
    string mobile = 2;
    string sex = 3;
}

然後運行maven指令
proto文件編譯
運行之後會發現在src/main/java/com/luxy/netty/proto下生成一個UserProto.java,說明protobuf在IDEA和Maven環境下配置成功

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章