1.环境配置:
1.1 maven配置:
<!-- protobuf的依赖 -->
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>3.10.0</version>
</dependency>
<build>
<!-- protobuf插件 -->
<extensions>
<extension>
<groupId>kr.motd.maven</groupId>
<artifactId>os-maven-plugin</artifactId>
<version>1.6.2</version>
</extension>
</extensions>
<!-- protobuf插件 -->
<plugins>
<plugin>
<groupId>org.xolstice.maven.plugins</groupId>
<artifactId>protobuf-maven-plugin</artifactId>
<version>0.5.0</version>
<configuration>
<!--默认值-->
<protoSourceRoot>${project.basedir}/src/main/protobuf/match_user_info/</protoSourceRoot>
<!--默认值-->
<!--<outputDirectory>${project.build.directory}/generated-sources/protobuf/java</outputDirectory>-->
<outputDirectory>${project.build.sourceDirectory}</outputDirectory>
<!--设置是否在生成java文件之前清空outputDirectory的文件,默认值为true,设置为false时也会覆盖同名文件-->
<clearOutputDirectory>false</clearOutputDirectory>
<!--默认值-->
<temporaryProtoFileDirectory>
${project.build.directory}/generated-sources/protobuf/java
</temporaryProtoFileDirectory>
<!--更多配置信息可以查看https://www.xolstice.org/protobuf-maven-plugin/compile-mojo.html-->
<protocArtifact>
<!-- com.google.protobuf:protoc:${protoc.version}:exe:${os.detected.classifier}-->
com.google.protobuf:protoc:3.10.0:exe:${os.detected.classifier}
</protocArtifact>
<!-- <pluginId>grpc-java</pluginId>-->
</configuration>
<!-- protobuf插件 -->
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>compile-custom</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
2.idea配置
idea下载protobuf support插件安装
3.开发
编写一个文件尾缀为.proto文件
// 如果使用此注释,则使用proto3; 否则使用proto2
syntax = “proto3”;
// 生成类的包名
option java_package = “com.protobuf.match_user_info”;
//生成的数据访问类的类名,如果没有指定此值,则生成的类名为proto文件名的驼峰命名方法
option java_outer_classname = “MathckUserInfoProtobuf”;
message Demo {
enum OsType {
UNKNOWN = 0;
ANDROID = 1;
IOS = 2;
}
OsType os_type=10;
string id = 2;
string did_md5 = 1;
}
4.编译:
输入输出的文件配pom的插件中进行配置,编译完成后可以看到生成的文件:
5.测试
MathckUserInfoProtobuf.Demo.Builder mathckUserInfoProtobuf = MathckUserInfoProtobuf.Demo.newBuilder();
mathckUserInfoProtobuf.setId("1");
mathckUserInfoProtobuf.setDidMd5("2222");
mathckUserInfoProtobuf.setOsType(MathckUserInfoProtobuf.Demo.OsType.ANDROID);
System.out.println(mathckUserInfoProtobuf.getId());
System.out.println(mathckUserInfoProtobuf.getDidMd5());
System.out.println(mathckUserInfoProtobuf.getOsType().getNumber());