1.引入protobuf依赖包
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>2.5.0</version>
</dependency>
2. 创建目录src/main/protobuf
注意: 这里必须要在src/main/protobuf目录下创建protobuf文件,是为了下面插件能访问
添加自定义的protobuf文件 - Student.proto
package raymessage;
option java_package = "com.my.student.protobuf";
option java_outer_classname = "StudentProtos";
/*MessageSignal.proto 文件 获取Student请求*/
message StudentReq {
required string name = 1;
required int32 version = 2; //0:最新版本,其他:指定版本
}
/*返回Student Result*/
message StudentRes {
required Result result = 1;
optional bytes content = 2; // Contains an Push content
optional string studentId = 3;
}
message Result {
enum ResultCode {
SUCCESS = 0;
FAILED = 1;
}
optional ResultCode resultCode = 1;
optional int32 errorCode = 2;
}
/*Student Content*/
message StudentContent {
optional string studentID = 1;
optional uint64 expireTime = 2;
}
3.添加插件
添加插件,使用maven编译时,能自动生成相应的java文件
<plugin>
<groupId>com.github.os72</groupId>
<artifactId>protoc-jar-maven-plugin</artifactId>
<version>2.5.0.2</version>
<executions>
<execution>
<phase>generate-sources</phase>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>
4.编译
maven clean install
结果入下:
5.完整的pom文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>my.protobuf</groupId>
<artifactId>my-protobuf</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>2.5.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>com.github.os72</groupId>
<artifactId>protoc-jar-maven-plugin</artifactId>
<version>2.5.0.2</version>
<executions>
<execution>
<phase>generate-sources</phase>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>