如何为通过 netty 消息解码器的每条消息分配一个序列号?

How to assign a sequence number to every message that passes a netty message decoder?

我正在开发一个 netty 通道 handler/decoder,它为到达处理程序的每条消息分配一个唯一的序列号。

我当前的方法定义了一个包含 AtomicLong 的属性作为计数器,每当有消息到达时,它就会递增 1 并分配给解码后的消息:

@Override
protected void decode(ChannelHandlerContext ctx, TextWebSocketFrame frame, List<Object> out) {
    AttributeKey<AtomicLong> sequenceKey = AttributeKey.valueOf("message_sequence");
    AtomicLong sequence = ctx.channel().attr(sequenceKey).get();
    long curerntMessageId = sequence.incrementAndGet();

    Message message = decode(frame);
    message.setMessageId(curerntMessageId);

稍后,在消息编码器中,消息id被传输到响应消息,从而通过唯一的id连接请求和响应。

采用这种方法的原因是,在网络套接字连接的上下文中,我需要一些机制来识别请求<->响应周期。

我想知道这种方法是否有意义,因为我必须一直访问频道属性,或者是否已经存在我可能不知道的现有解决方案?

如果这只需要每个连接都是唯一的,您可以直接在解码器本身中存储一个 int / long 并递增它。这是有效的,因为一切都是单线程的。因此,如果我正确理解您的用例,则根本不需要使用属性和原子