Netty 关联请求和响应

Netty Correlating Request and Responses

我想为 TCP 二进制协议编写代理。我使用 Netty 存储库中的 HexDump 示例作为指南。 https://github.com/netty/netty/tree/4.1/example/src/main/java/io/netty/example/proxy

这很好用。但我有时想根据原始请求修改响应

环顾四周,似乎使用入站通道 AttributeMap 可能是存储此类请求详细信息的地方。 (下面有更多详细信息)

io.netty.util.AttributeMap

但是虽然它有点工作有时一个请求会覆盖另一个请求的详细信息

这是有道理的,Netty 是异步的,你不能真正保证什么时候会发生。

所以我想知道如何可靠地将每个请求与响应相关联。注意我不能 更改协议,这可能是在请求和响应之间传递详细信息的一种方式。

感谢您的见解。

HexDumpFrontendHandler

@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) throws InterruptedException {
…
ctx.channel().attr(utils.REQUEST_ATTRIBUTE).set(requestDetails);
…
}

@Override
public void channelActive(ChannelHandlerContext ctx) {
    final Channel inboundChannel = ctx.channel();

    // Start the connection attempt.
    Bootstrap b = new Bootstrap();
    b.group(inboundChannel.eventLoop())
     .channel(ctx.channel().getClass())
     .handler(new HexDumpBackendHandler(inboundChannel))
     .option(ChannelOption.AUTO_READ, false);

    ChannelFuture f = b.connect(remoteHost, remotePort);
    outboundChannel = f.channel();
    f.addListener((ChannelFutureListener) future -> {
        if (future.isSuccess()) {
            // connection complete start to read first data
            inboundChannel.read();
        } else {
            // Close the connection if the connection attempt has failed.
            inboundChannel.close();
        }
    });
}

HexDumpBackendHandler

@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) {
…
RequestDetails requestDetails = inboundChannel.attr(utils.REQUEST_ATTRIBUTE).getAndRemove();
…
}

我的解决方案(变通方法?)如下。我正在使用的协议不能保证每个请求在全球范围内都有唯一的标识符,但它确实唯一地标识了 tcp 连接中的请求。

所以下面的组合允许我创建一个 ConcurrentHashMap 以下面的作为键 主机 + 临时端口 + 连接的本地标识符

这适用于我的情况。我确信他们在 Netty 框架本身内解决它的其他方法