protobuf生成java代码

[亡魂溺海] 提交于 2020-01-15 04:28:08

protobuf官方包下载:https://github.com/protocolbuffers/protobuf/releases/tag/v3.11.1

1、Idea中安装protobuf插件,重启Idea

2、idea中新建maven项目protobuf-demo

3、pom.xml中添加如下依赖

<properties>
    <project.build.sourceEncoding>
UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
    <dependency>
        <groupId>
com.google.protobuf</groupId>
        <artifactId>
protobuf-java</artifactId>
        <version>
3.6.1</version>
    </dependency>
    <dependency>
        <groupId>
junit</groupId>
        <artifactId>
junit</artifactId>
        <version>
4.13</version>
        <scope>
test</scope>
    </dependency>
</dependencies>
<build>
    <extensions>
        <extension>
            <groupId>
kr.motd.maven</groupId>
            <artifactId>
os-maven-plugin</artifactId>
            <version>
1.4.1.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:3.1.0:exe:${os.detected.classifier}
               
</protocArtifact>
                <pluginId>
grpc-java</pluginId>
            </configuration>
            <executions>
                <execution>
                    <goals>
                        <goal>
compile</goal>
                        <goal>
compile-custom</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

4、在idea中编写proto文件,目录结构如下

 

内容如下:

syntax = "proto3";
option java_package = "com.black.model";
option java_outer_classname = "PersonModel";
message Person {
    int32 id = 1;
    string name = 2;
    string email = 3;
}
5、生成java

 

6、测试代码

public class PersonModelTest {
    public static void main(String[] args) throws InvalidProtocolBufferException {
        PersonModel.Person.Builder builder= PersonModel.Person.newBuilder();
        builder.setId(1);
        builder.setEmail("lee@sunvalley.com.cn");
        builder.setName("lee");

        PersonModel.Person person= builder.build();
        System.out.print("====before===="+person);
        System.out.println("==================");
        for(Byte b:person.toByteArray()){
            System.out.print(b);
        }
        System.out.println("==================");
        byte[] byteArray= person.toByteArray();
        PersonModel.Person p2 = PersonModel.Person.parseFrom(byteArray);
        System.out.println("=========反序列化生成对象,转换之后==========");
        System.out.println(p2.getId()+","+p2.getEmail()+","+p2.getName());
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!