protobuf转换方法
- 编写protobuf代码如下:
package netty;option java_package = "com.clq.netty.protoc";option java_outer_classname = "SubsribeReqProto";message SubScribeReq{ required int32 subReqID = 1; required string userName = 2; required string productName = 3; repeated string address = 4;}
package netty;option java_package = "com.clq.netty.protoc";option java_outer_classname = "SubsribeRespProto";message SubScribeResp{ required int32 subReqID = 1; required string respCode = 2; required string desc = 3;}
2 . 执行如下命令(首先下载proto.exe 地址:):
E:\tmp\protoc-2.5.0-win32> ./protoc.exe --java_out=./ SubscribeReq.protoE:\tmp\protoc-2.5.0-win32> ./protoc.exe --java_out=./ SubscribeResp.proto
3 . 拷贝生成代码到IDE编辑器,下载地址见: 如果报错,则添加protobuf-java
com.google.protobuf protobuf-java 2.5.0
4 . 执行测试protobuf测试
package com.clq.netty.protoc;import com.google.protobuf.InvalidProtocolBufferException;import java.util.ArrayList;import java.util.List;/** * Created by clq on 2018/7/24. */public class TestSubsribeReqProto { private static byte[] encode(SubsribeReqProto.SubScribeReq req) { return req.toByteArray(); } private static SubsribeReqProto.SubScribeReq decode(byte[] body) throws InvalidProtocolBufferException { return SubsribeReqProto.SubScribeReq.parseFrom(body); } private static SubsribeReqProto.SubScribeReq createSubScripeReq() { SubsribeReqProto.SubScribeReq.Builder builder = SubsribeReqProto.SubScribeReq.newBuilder(); builder.setSubReqID(1); builder.setUserName("clq"); builder.setProductName("xxxx usb key"); Listaddress = new ArrayList<>(); address.add("河南郑州"); address.add("河南洛阳"); builder.addAllAddress(address); return builder.build(); } public static void main(String[] args) { SubsribeReqProto.SubScribeReq subScripeReq = createSubScripeReq(); System.out.println("Before encode:" + subScripeReq.toString()); SubsribeReqProto.SubScribeReq subScripeReq1 = createSubScripeReq(); System.out.println("After encode:" + subScripeReq1); System.out.println("Assert equ:" + subScripeReq1.equals(subScripeReq)); }}
5 . 打印结果
Before encode:subReqID: 1userName: "clq"productName: "xxxx usb key"address: "\346\262\263\345\215\227\351\203\221\345\267\236"address: "\346\262\263\345\215\227\346\264\233\351\230\263"After encode:subReqID: 1userName: "clq"productName: "xxxx usb key"address: "\346\262\263\345\215\227\351\203\221\345\267\236"address: "\346\262\263\345\215\227\346\264\233\351\230\263"Assert equ:true