netty重用 channel

标签 netty channels

我想创建一个重用 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/

相关文章:

java - Netty 中的 ByteBuffers 导致内存泄漏

java - 可用于单元测试的 Netty 4/5 确定性缓冲区泄漏检测

html - 使用 Netty HTTP2 实现支持服务器发送事件

java - 如何在其他类中读取netty中的消息

concurrency - 在 Golang 中同时读取多个 channel

antlr4 - antlr 4.5 中的额外 channel

java - 高负载下正常GC的jvm配置

go - 如果没有进一步的语句要执行,为什么 time.Sleep 不起作用?

go - "channel1 <- <-channel2"是做什么的?

node.js - 从 Buffer nodejs 中分离 4 个 channel