如果使用通道池,则添加侦听器/返回future以获取http响应

时间:2016-04-01 05:49:28

标签: netty

我想用连接池实现一个简单的异步http客户端。

这是我的连接池地图。

channelPool = new AbstractChannelPoolMap<InetSocketAddress, ChannelPool>() {
        @Override
        protected ChannelPool newPool(InetSocketAddress key) {
            Bootstrap bootstrap = getBootstrap().remoteAddress(key);
            return new FixedChannelPool(bootstrap, nett4HttpClientInitializer, maxConnectionsPerHost);
        }
    };

这是netty4HttpClientInitializer

public void channelCreated(Channel ch) throws Exception {
        SocketChannel channel = (SocketChannel) ch;
        channel.config().setKeepAlive(true);
        channel.config().setTcpNoDelay(true);
        if (connectTimeout > 0) {
            channel.config().setConnectTimeoutMillis(connectTimeout);
        }
        ChannelPipeline pipeline = channel.pipeline();
        // Enable HTTPS if necessary.
        if (sslContext != null) {
            pipeline.addLast(sslContext.newHandler(channel.alloc()));
        }
        if (proxy != null) {
            if (proxyUser != null && !proxyUser.trim().isEmpty()) {
                pipeline.addLast(new HttpProxyHandler(proxy, proxyUser, proxyPassword));
            } else {
                pipeline.addLast(new HttpProxyHandler(proxy));
            }
        }
        pipeline.addLast(new HttpClientCodec());
        pipeline.addLast(new HttpContentDecompressor());
        pipeline.addLast(new HttpObjectAggregator(maxResponseSize));
        if (readTimeout > 0) {
            pipeline.addLast(new ReadTimeoutHandler(readTimeout, TimeUnit.MILLISECONDS));
        }}

问题是,如果我将一个SimpleChannelInboundHandler添加到netty4HttpClientInitializer,我认为它将被调用pool.acquire()的每个线程共享。

你能帮我把SimpleChannelInboundHandler变成无状态吗? channelRead0中的监听器?执行任务-channelContext.executor()。submit()?

P.S。我从netty事件循环之外调用pool.acquire()。我希望通过HttpResponse获得未来。

0 个答案:

没有答案