将Netty ByteBuf转换为POJO

问题描述

我已经使用Netty和Spring Boot设置了TCP服务器。我的服务器通过TCP接收固定长度的字节缓冲区,将其转换为POJO,对其进行持久化处理,返回适当的响应并关闭通道。

POJO是:

public class DataModel {
    
    private Integer id;
    private String name;
    private Integer code;

// Getters and Setters and ...

public DataModel(byte[] bytes) {
        setId((Integer) Byte.toUnsignedInt(bytes[0]));
        setName(new String(Arrays.copyOfRange(bytes,1,5)));
        setCode( (Integer) Byte.toUnsignedInt(bytes[5]));
        
    }

对于处理输入数据,我有两种选择:

I。创建一个扩展BytetoMessageDecoder类的Decoder类:

public class Decoder extends BytetoMessageDecoder{

    @Override
    protected void decode(ChannelHandlerContext ctx,ByteBuf in,List<Object> out) throws Exception {
    
        int length = in.readableBytes();
        byte[] bytes = new byte[length];
        in.getBytes(in.readerIndex(),bytes);
        out.add(new DataModel(bytes));
    }

,然后将其添加到ServerChannelInitializer:

....
Decoder decoder = new Decoder();
decoder.setSingleDecode(true);
socketChannel.pipeline().addLast("myDec",decoder);
....

这是标准的netty例程。但是我有一些问题,例如服务器接收入站缓冲区两次。我想我应该在我的解码器之前添加一个LengthFieldBasedFrameDecoder,为此我必须更改消息格式(向消息中添加帧长)。

II。另一种方法是直接在ChannelHandler中实现业务逻辑:

....
@Override
    public void channelRead(ChannelHandlerContext ctx,Object msg) throws Exception {

// Same Decoder business here

        ctx.flush();
        ctx.close();
    }
...
    

我的服务器不会有大流量:最大并发连接数最多为10,000,消息大小小于100字节。

这两种方法之间是否存在显着差异(例如性能)?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)