使用样例
服务端主要代码(注意bossgroup为2,workgroup为2):
final EchoServerHandler serverHandler = new EchoServerHandler();
EventLoopGroup bossGroup = new NioEventLoopGroup(2);
EventLoopGroup workgroup = new NioEventLoopGroup(2);
try {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup, workgroup)
.channel(NioServerSocketChannel.class)
.localAddress(new InetSocketAddress(port))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline().addLast(serverHandler);
}
});
ChannelFuture f = bootstrap.bind().sync();
f.channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully().sync();
}
完整代码例子:https://github.com/XiaotaoYi/Netty/tree/master/samples/echo
主从多线程模型工作原理


引用链接:http://www.infoq.com/cn/articles/netty-threading-model
源码调试理解主从多线程模型
知识点:
多线程模型:Netty的多线程模型也即对应多个NioEventLoop模型(一个线程对应一个NioEventLoop)
主多线程模型:也即boss线程模型,用于accept客户端的链接。
从线程模型:也即worker线程模型,用于处理I/O的读写操作和业务操作。
问题1:netty什么时候创建boss线程?
答:如下图SingleThreadEventExecutor.doStartThread中(line847)创建一个boss NIO线程,也即在调用样例代码 ChannelFuture f = bootstrap.bind().sync()时创建。这里有一个注意事项“客户端访问十次以上的链接请求,boss线程仍然不会增加”。

问题2:netty什么时候创建worker线程?
答:如下图在boss线程中创建(nioEventLoopGroup-2-1为问题1在程序启动时创建的boss线程),因为boss线程需要将客户端请求对应的socketChannel注册到worker线程。

客户端请求超过10次以上,服务端的表象如下:
1、对于每一个客户端请求,boss线程会采用"轮询worker线程机制"选择一个worker线程去处理后续I/O的读写操作(选择具体代码体现在MultithreadEventLoopGroup.register(Channel channel)中)。
网友评论