我想创建一个重用 channel 的连接池,但我想不出来
执行这个测试
public void test() {
ClientBootstrap client = new ClientBootstrap(new NioClientSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));
client.setPipelineFactory(new ClientPipelineFactory());
// Connect to server, wait till connection is established, get channel to write to
Channel channel = client.connect(new InetSocketAddress("192.168.252.152", 8080)).awaitUninterruptibly().getChannel();
{
// Writing request to channel and wait till channel is closed from server
HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "test");
String xml = "xml document here";
ChannelBuffer buffer = ChannelBuffers.copiedBuffer(msgXml, Charset.defaultCharset());
request.addHeader(HttpHeaders.Names.CONTENT_LENGTH, buffer.readableBytes());
request.addHeader(HttpHeaders.Names.CONTENT_TYPE, "application/xml");
request.setContent(buffer);
channel.write(request).awaitUninterruptibly().getChannel().getCloseFuture().awaitUninterruptibly();
channel.write(request).awaitUninterruptibly().getChannel().getCloseFuture().awaitUninterruptibly();
}
client.releaseExternalResources();
}
我在第二个 channel 中得到了一个 ClosedChannelException.write(request)....
存在重用 channel 的方法吗?还是保持 channel 畅通?
提前致谢
最佳答案
第二次写入失败是因为服务器关闭了连接。
服务器关闭连接的原因是你添加HTTP头失败
Connection: Keep-Alive
原始请求。
这是保持 channel 打开所必需的(这是您在这种情况下想要做的)。
channel 关闭后,您必须创建一个新 channel 。您不能重新打开 channel 。 Channel.getCloseFuture() 返回的 ChannelFuture 对 channel 来说是最终的(即常量),一旦 isDone() 在这个 future 返回 true
,它就不能被重置。这就是关闭的 channel 不能被重用的原因。
但是,您可以根据需要多次重复使用开放 channel ;但是您的应用程序必须正确地使用 HTTP 协议(protocol)才能完成此操作。
关于netty重用 channel ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13368470/