Netty:我如何重用相同的`FullHttpResponse`?

时间:2016-06-04 02:52:18

标签: java http netty

在我的项目中,我想为许多客户编写相同的FullHttpResponse以提升性能。

以前我为自定义协议编写了​​相同的ByteBuf,并使用retain来阻止写入后释放buf。

不幸的是FullHttpResponseDefaultFullHttpResponse)我的技术似乎不起作用。我第一次写响应时,客户端会正确接收响应,但下一次写操作不会通过。

我做了一个简单的System.out.println测试,以确保没有任何阻塞,我的代码完全执行,我的测试显示是,没有任何阻塞,请求似乎确实已经完成。

我正在使用Maven Central发布的Netty 4.1.0.Final

管道只有HttpServerCodec(256, 512, 512, false, 64)和我的SimpleChannelInboundHandler<HttpRequest>,我从FullHttpResponse发送了class HTTPHandler extends SimpleChannelInboundHandler<HttpRequest> { private static final FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.buffer(8).writeLong(0), false); @Override public void channelRead0(ChannelHandlerContext ctx, HttpRequest msg) { ctx.writeAndFlush(response.retain(), ctx.voidPromise()); } }

这是我的入站处理程序的简化版本:

// Setup
var collection = {
    2548: {
      album: "Slippery When Wet",
      artist: "Bon Jovi",
      tracks: [ 
        "Let It Rock", 
        "You Give Love a Bad Name" 
      ]
    },
    2468: {
      album: "1999",
      artist: "Prince",
      tracks: [ 
        "1999", 
        "Little Red Corvette" 
      ]
    },
    1245: {
      artist: "Robert Palmer",
      tracks: [ ]
    },
    5439: {
      album: "ABBA Gold"
    }
};
// Keep a copy of the collection for tests
var collectionCopy = JSON.parse(JSON.stringify(collection));

// Only change code below this line

1 个答案:

答案 0 :(得分:3)

您需要使用response.duplicate().retain(),或者如果使用Netty 4.1.x,您也可以使用response.retainedDuplicate()

这是确保您获得单独的读/写索引所必需的。