java - Netty:回调在哪里?

标签 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);
}

最佳答案

如果需要运行阻塞操作,则需要在执行阻塞操作的 ChannelHandler 前面放置一个 ExecutorHandler。这会将所有 ChannelHandler 从 EventLoop(IO 线程)“移动”到另一个线程,从而“解锁”EventLoop。

参见[1]

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

关于java - Netty:回调在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15286846/

相关文章:

asynchronous - 了解 netty 的工作原理

java - Netty3.2 API 中的超时示例( IdleStateHandler 和 ReadTimeoutHandler )不适用于服务器

java - 异常在线程 "main"java.lang.UnsatisfiedLinkError : RunnerClass. parsecmdline(ILjava/lang/String;)V

linux - HDFS 是如何同时向下层本地文件系统写入多个文件的呢?

swift - 用于在管道结果时链接异步操作的 GCD 模式

events - F# 中的松散耦合代理

java - Micronaut 是否需要异步编程?

java - 是否可以定义一个 Java 类加载器,它返回与所请求的完全不同的类?

java.util.zip.ZipException : oversubscribed dynamic bit lengths tree

java - Java实现循环调度算法