Netty服务器线程模型概览
?
ServerBootstrap负责初始话netty服务器,并且开始监听端口的socket请求。
客户端送入的消息会首先由许多UpstreamHandler依次处理,处理得到的数据送入应用的业务逻辑handler,通常用SimpleChannelUpstreamHandler来实现这一部分。
?
public class DatabaseGatewayPipelineFactory implements ChannelPipelineFactory {? private final ExecutionHandler executionHandler;? public DatabaseGatewayPipelineFactory(ExecutionHandler executionHandler) { this.executionHandler = executionHandler; }? public ChannelPipeline getPipeline() { return Channels.pipeline( new DatabaseGatewayProtocolEncoder(), new DatabaseGatewayProtocolDecoder(), executionHandler, // 多个pipeline之间必须共享同一个ExecutionHandler new DatabaseQueryingHandler());//业务逻辑handler,IO密集 } }把共享的ExecutionHandler实例放在业务逻辑handler之前即可,注意ExecutionHandler一定要在不同的pipeline之间共享。它的作用是自动从ExecutionHandler自己管理的一个线程池中拿出一个线程来处理排在它后面的业务逻辑handler。而worker线程在经过ExecutionHandler后就结束了,它会被ChannelFactory的worker线程池所回收。
它的构造方法是ExecutionHandler(Executor executor) ,很显然executor就是ExecutionHandler内部管理的线程池了。netty额外给我们提供了两种线程池:
MemoryAwareThreadPoolExecutor和OrderedMemoryAwareThreadPoolExecutor,它们都在org.jboss.netty.handler.execution 包下。
MemoryAwareThreadPoolExecutor确保jvm不会因为过多的线程而导致内存溢出错误,OrderedMemoryAwareThreadPoolExecutor是前一个线程池的子类,除了保证没有内存溢出之外,还可以保证channel event的处理次序。具体可以查看API文档,上面有详细说明。
原文链接:?http://blog.cogipard.org/articles/netty-server-thread-architecture
?
?
1 楼 zbmartin 2012-07-22 楼主写的很不错,一般都是用本身自带的 ExecutionHandler 来实现wrok线程的优化