Protobuf生成java类的方式

4,371 阅读1分钟

背景

最近开始使用grpc(google的rpc框架),grpc使用了protobuf文件作为序列化,protobuf适合做数据存储和RPC 数据交换格式,下面介绍下如何将protobuf文件生成对应的java类

protoc命令

下载源码

git clone https://github.com/google/protobuf

git checkout 版本号

安装 automake和 Libtool

brew install automake

brew install libtool

运行自动生成脚本

./autogen.sh

安装protobuf

./configure
make check
make
sudo make install 

查看安装版本

protoc –version

执行编译命令

protoc --proto_path=src --java_out=src/main/java src/main/proto/xxx.proto

mvn命令

pom文件引入插件

<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>
            <extensions>true</extensions>
            <configuration>
                <!-- The version of protoc must match protobuf-java. If you don't depend
                  on protobuf-java directly, you will be transitively depending on the protobuf-java
                  version that grpc depends on. -->
                <protocArtifact>com.google.protobuf:protoc:3.2.0:exe:${os.detected.classifier}</protocArtifact>
                <clearOutputDirectory>false</clearOutputDirectory>
                <outputDirectory>src/main/java</outputDirectory>
                <pluginId>grpc-java</pluginId>
                <pluginArtifact>io.grpc:protoc-gen-grpc-java:1.3.0:exe:${os.detected.classifier}</pluginArtifact>

            </configuration>
            <executions>
                <execution>
                    <goals>
                        <goal>compile</goal>
                        <goal>compile-custom</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
        
    </plugins>
</build>

编译命令

-   protobuf:compile
-   protobuf:compile-custom