protobuf java小栗子

protobuf java小栗子

近来在项目中发现用到了Protocol Buffers,作为netty传输的协议,通过写个例子进行感受下其高效的序列化和反序列化~

1. 所用环境windows ,语言java

下载生成器与对应版本的jar包
当前例子所用:protoc.exe, protobuf-java-2.4.1.jar

2. 编写proto文件,例子如下:

package org.demo.protobuf;
option java_package = "org.demo.protobuf";
option java_outer_classname = "MsgSendProto";

message MsgSend {
  required string msgID = 1;
  required string phone = 2;
  required int64 doneTime = 3;
  required int32 enterpriseID = 4;
  optional string enterpriseName = 5;
  required int32 result = 6;
  required int32 channelID = 7;
  required int32 carrier = 8;
  required int32 busyType = 9;
  optional int32 size = 10;
  optional int32 unit = 11;
}

3. 在protoc.exe所在目录打开cmd,用以下命令执行编译刚刚编写proto文件,成功后无消息输出,在相应的目录下会产生java文件MsgSendProto.java

protoc.exe --java_out=./ MsgSend.proto

protobuf java小栗子_第1张图片

4. 在工程中导入protobuf-java-2.4.1.jar,编写个简单的测试类,感受下其序列化与反序列化~

public class MsgSendProtoBufTest {
    public static void main(String[] args) {
        // 先进行序列化
        MsgSendProto.MsgSend.Builder builder = MsgSendProto.MsgSend.newBuilder();
        builder.setMsgID("20151101");
        builder.setPhone("13100000000");
        builder.setDoneTime(System.currentTimeMillis());
        builder.setEnterpriseID(1);
        builder.setEnterpriseName("enterprise");
        builder.setResult(1);
        builder.setChannelID(1);
        builder.setCarrier(1);
        builder.setBusyType(1);
        builder.setSize(5);
        builder.setUnit(1);
        MsgSendProto.MsgSend msgSend = builder.build();
        byte[] buf = msgSend.toByteArray();
        try {
            // 再反序列化输出看看
            MsgSendProto.MsgSend msgReceive = MsgSendProto.MsgSend.parseFrom(buf);
            System.out.println(msgReceive.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(buf);
    }
}

结果输出,表明能正常序列化与反序列化~
protobuf java小栗子_第2张图片

你可能感兴趣的:(java)