|
1.MessagePack简单示例 1.1 引入jar包 <dependency>
<groupId>org.msgpack</groupId>
<artifactId>msgpack</artifactId>
<version>0.6.12</version>
</dependency>
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<ByteBuf> {
@Override
protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> 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<Object> {
@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<Object> {
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object o) throws Exception {
System.out.println("o:" + o);
}
} |
2.4 结果打印 o:["22c1a6ba-cbc1-4a88-874d-470fed3cde5d","我是jarye"]
----------------------------
原文链接:https://www.jianshu.com/p/937a3a457c75
程序猿的技术大观园:www.javathinker.net
[这个贴子最后由 flybird 在 2021-08-30 20:52:28 重新编辑]
|
|