Netty:回调在哪里?

时间:2013-03-08 04:39:58

标签: java asynchronous netty

我最近开始使用JBoss Netty,到目前为止我的理解是每次服务器收到请求时都会使用channelPipelineFactory来创建ChannelPipeline。 ChannelPipeline包含一系列处理请求的ChannelHandler。现在的问题是,如果我的管道中的一个处理程序需要从数据库中获取数据,这就是阻塞I / O.请求的处理被阻止了?这与Servlet的常规请求处理有什么不同?我对来自NodeJS的事件驱动的异步I / O的理解是,有一个事件循环,并且有一系列回调函数被注册用于阻塞I / O操作,并且只要I / O完成就会调用这些函数。 Netty的等价物是什么?

private static final HttpResponseEncoder httpResponseEncoder = new HttpResponseEncoder();
private static final JsonEncoder jsonEncoder = new JsonEncoder();
private static final ExecutionHandler executionHandler = new ExecutionHandler(
        new OrderedMemoryAwareThreadPoolExecutor(5, 1048576, 1048576));

public static void main(String[] args) throws Exception {
    ChannelFactory factory = new NioServerSocketChannelFactory(Executors.newCachedThreadPool(),
            Executors.newCachedThreadPool());
    SocketAddress sockAddress = new InetSocketAddress(8080);

    RedisClient client = new RedisClient("127.0.0.1");
    final RedisAsyncConnection<String, String> connection = client.connectAsync();

    ServerBootstrap bootstrap = new ServerBootstrap(factory);
    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
        @Override
        public ChannelPipeline getPipeline() throws Exception {
            ChannelPipeline pipeline = Channels.pipeline();
            pipeline.addLast("executionHandler", executionHandler);
            pipeline.addLast("weightedRandomGenerator", new WeightedRandomNumberGenerator(
                    connection));
            pipeline.addLast("encoder", httpResponseEncoder);
            pipeline.addLast("JsonConverter", jsonEncoder);
            return pipeline;
        }
    });
    bootstrap.setOption("child.tcpNoDelay", true);
    bootstrap.setOption("child.keepAlive", true);
    bootstrap.bind(sockAddress);
}

1 个答案:

答案 0 :(得分:2)

如果需要运行被阻止的操作,则需要在执行阻塞操作的ChannelHandler前面放置一个ExecutorHandler。这将&#34;移动&#34; EventLoop(IO-Thread)中的所有ChannelHandler到另一个Thread,因此&#34; unblock&#34; EventLoop。

见[1]

[1] http://netty.io/3.6/api/org/jboss/netty/handler/execution/ExecutionHandler.html