我最近开始使用 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/