VDev
VDev

Reputation: 2344

Netty: Where is the callback?

I have recently started working with JBoss Netty and my understanding so far is that a channelPipelineFactory is used to create a ChannelPipeline, each time a request is received by the server. A ChannelPipeline contains a series of ChannelHandlers that process the request. Now the question I have is, If one of the handlers in my pipeline needs to fetch data from a database, this is Blocking I/O.The processing of the request is blocked? How is this any different from a regular request processing by say a Servlet? My understanding of event driven async I/O coming from NodeJS is that there is one event loop and there are a series of callback functions registered for blocking I/O operations, and these get invoked whenever the I/O is complete. What is the equivalent in 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);
}

Upvotes: 2

Views: 2366

Answers (1)

Norman Maurer
Norman Maurer

Reputation: 23567

If you need to run blocked operations you need to place an ExecutorHandler in front of your ChannelHandler that does the blocking operation. This will "move" all the ChannelHandlers from the EventLoop (IO-Thread) to an other Thread and so "unblock" the EventLoop.

See [1]

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

Upvotes: 3

Related Questions