netty和mina都出自于同一个作者,所以netty和mina的多线程模型,除了一些细节方面,大体的模型基本是一样的。本文在分析源码的过程中,也会适当对这些细节做一个对比。(注:netty源码版本为netty-4.0.2.Final)

1. 端口绑定

         不同于mina,netty采用了一个线程池来监听不同的端口。

final ChannelFuture initAndRegister() {
final Channel channel = channelFactory().newChannel();
try {
init(channel);
} catch (Throwable t) {
......
}


ChannelPromise regPromise = channel.newPromise();
group().register(channel, regPromise);
......
}
public ChannelFuture register(Channel channel, ChannelPromise promise) {
return next().register(channel, promise);
}
public EventExecutor next() {
return children[Math.abs(childIndex.getAndIncrement() % children.length)];
}


        这里的EventExecutor对应一个线程,端口监听选择线程的策略跟mina选择IOProcessor类似,采用了轮转的方式。这里有一点要注意的是在init方法中,添加了一个ServerBootstrapAcceptor,这个类将用来处理后面的连接请求。

void init(Channel channel) throws Exception {
......
p.addLast(new ChannelInitializer<Channel>() {
@Override
public void initChannel(Channel ch) throws Exception {
ch.pipeline().addLast(new ServerBootstrapAcceptor(
currentChildGroup, currentChildHandler, currentChildOptions, currentChildAttrs));
}
});
}


2. 连接监听

        现在来看连接请求的处理。服务器在收到连接后,数据传递给ServerBootstrapAcceptor。

public void channelRead(ChannelHandlerContext ctx, Object msg) {
Channel child = (Channel) msg;

child.pipeline().addLast(childHandler);
......


try {
childGroup.register(child);
} catch (Throwable t) {
......
}
}


        该方法首先把childHandler(业务逻辑处理)加入到pipeline的最后,然后将child 注册到childGroup中,这里的childGroup和端口绑定中的group()有着相同的实现。所以也将选择一个特定的线程来处理该child上的IO请求。默认childGroup的大小为系统内核数*2。这里的实现跟mina是相似的。

3. IO处理

        在线程监听到有读请求时,将调用pipeline做进一步的处理。这里的pipeline实际上跟mina的FilterChain是一样的,只是概念上的差别。

有一点比较奇怪的是,作者在这个版本似乎有意去掉了ExecutionHandler,所以现在需要自己实现一个来并发处理业务逻辑,尤其是像文件传输,数据库查询这些操作,是很有必要的。


        总的来看,在多线程方面,netty跟mina最主要的区别是连接监听的多线程设计,这点可能是要优于mina的。