MessagePack反序列化使用示例

上一篇 <<<序列化与反序列化知识点汇总
下一篇 >>>Marshalling在Netty中的使用


1.MessagePack简单示例

1.1 引入jar包


org.msgpack
msgpack
0.6.12

1.2 传输对象必须要引入注解@Message,且要有默认构造函数

@Message
public class MsgEntity {

    private String id;
    private String name;

    public MsgEntity() {

    }
……
}

1.3 demo演示

// 创建MessagePack
        MessagePack messagePack = new MessagePack();
        MsgEntity meite = new MsgEntity(UUID.randomUUID().toString(), "我是jarye");
        // 序列化
        byte[] bs = messagePack.write(meite);
        Value read1 = messagePack.read(bs);
        System.out.println(read1);
//        // 反序列化
        MsgEntity read = messagePack.read(bs, MsgEntity.class);
        System.out.println(read);

1.4 结果打印

["e1efc641-469d-4c6e-a765-e46edf0052e0","我是jarye"]
com.jgspx.serialize.messagepack.MsgEntity@62e136d3

2.MessagePack在netty中的使用

2.1 netty中编码器和解码器定义

public class MsgpackDecoder extends MessageToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List list) throws Exception {
        final int length = byteBuf.readableBytes();
        byte[] b = new byte[length];
        byteBuf.getBytes(byteBuf.readerIndex(), b, 0, length);
        MessagePack msgpack = new MessagePack();
        list.add(msgpack.read(b));
    }
}
public class MsgpackEncoder extends MessageToByteEncoder {

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Object msg, ByteBuf byteBuf) throws Exception {
        MessagePack msgpack = new MessagePack();
        byteBuf.writeBytes(msgpack.write(msg));
    }
}
 
 

2.2 注册到netty中

ch.pipeline().addLast(new MsgpackDecoder());
ch.pipeline().addLast(new MsgpackEncoder());

2.3 数据传输和接收可以直接使用对象形式了

public class ClientHandler extends SimpleChannelInboundHandler {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        MsgEntity msgEntity = new MsgEntity(UUID.randomUUID().toString(), "我是jarye");
        ctx.writeAndFlush(msgEntity);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object o) throws Exception {
        System.out.println("resp:"+o);
    }
}
public class ServerHandler extends SimpleChannelInboundHandler {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object o) throws Exception {
        System.out.println("o:" + o);
    }
}
 
 

2.4 结果打印

o:["22c1a6ba-cbc1-4a88-874d-470fed3cde5d","我是jarye"]


推荐阅读:
<< << << << << << << << << << << << <<<粘包和拆包问题解决方案汇总
<<<序列化与反序列化知识点汇总
<<

你可能感兴趣的:(MessagePack反序列化使用示例)