1、下载对应的包文件,比如我这里下载的是protoc-3.6.1-win32.zip,解压后将其bin路径加入到系统的PATH环境变量中;
在cmd窗口中执行protoc --version来检查protoc是否正确安装;
2、编写protoBuf文件:
1 syntax = "proto2"; 2 3 package protocol; 4 5 option java_package = "com.demo.prototest"; 6 option java_outer_classname = "BaseRequestProto"; 7 8 message RequestProtocol { 9 required int32 requestId = 2; 10 required string regMsg = 1; 11 }
1 syntax = "proto2"; 2 3 package protocol; 4 5 option java_package = "com.demo.prototest"; 6 option java_outer_classname = "BaseResponseProto"; 7 8 message ResponseProtocol { 9 required int32 responseId = 2; 10 required string resMsg = 1; 11 }
3、编译proto文件:
protoc --java_out=/dev BaseRequestProto.proto BaseResponseProto.proto
protoc 命令将刚才定义的协议格式转换为 Java 代码,并生成在 /dev 目录。
4、引入POM文件:
1 <dependency> 2 <groupId>com.google.protobuf</groupId> 3 <artifactId>protobuf-java</artifactId> 4 <version>3.4.0</version> 5 </dependency>
5、实现protoBuf编码解码测试代码:
1 public static void main(String[] args) throws InvalidProtocolBufferException { 2 BaseRequestProto.RequestProtocol protocol = BaseRequestProto.RequestProtocol.newBuilder() 3 .setRequestId(123) 4 .setRegMsg("hello, protobuf and world") 5 .build(); 6 7 byte[] encode = encode(protocol); 8 9 BaseRequestProto.RequestProtocol parseFrom = decode(encode); 10 11 System.out.println(protocol.toString()); 12 System.out.println(protocol.toString().equals(parseFrom.toString())); 13 } 14 15 public static byte[] encode(BaseRequestProto.RequestProtocol protocol){ 16 return protocol.toByteArray() ; 17 } 18 19 public static BaseRequestProto.RequestProtocol decode(byte[] bytes) throws InvalidProtocolBufferException { 20 return BaseRequestProto.RequestProtocol.parseFrom(bytes); 21 }