線程模型是Netty的核心設計,設計地很巧妙,之前項目中有一塊處理並發的設計和Netty的Eventloop單線程設計類似,效果得到了實證。
Netty5的類層次結構和之前的版本變化很大,網上也有很多文章寫Netty的線程模型,Reactor模式,比如這篇http://blog.csdn.net/xiaolang85/article/details/37873059, 應該是引自《Netty權威指南》,寫得比較全面,但是有幾個關鍵的概念沒講清楚。
這篇文章只講Netty5線程模型最重要的幾個關鍵點
第一個概念是如何理解NioEventLoop和NioEventLoopGroup:NioEventLoop實際上就是工作線程,可以直接理解為一個線程。NioEventLoopGroup是一個線程池,線程池中的線程就是NioEventLoop。Netty設計這幾個類的時候,層次結構挺復雜,反而讓人迷惑。
還有一個讓人迷惑的地方是,創建ServerBootstrap時,要傳遞兩個NioEventLoopGroup線程池,一個叫bossGroup,一個叫workGroup。《Netty權威指南》里只說了bossGroup是用來處理TCP連接請求的,workGroup是來處理IO事件的。
這么說是沒錯,但是沒說清楚bossGroup具體如何處理TCP請求的。實際上bossGroup中有多個NioEventLoop線程,每個NioEventLoop綁定一個端口,也就是說,如果程序只需要監聽1個端口的話,bossGroup里面只需要有一個NioEventLoop線程就行了。
在上一篇文章介紹服務器端綁定的過程中,我們看到最后是NioServerSocketChannel封裝的Java的ServerSocketChannel執行了綁定,並且執行accept()方法來創建客戶端SocketChannel的連接。一個端口只需要一個NioServerSocketChannel即可。
- EventLoopGroup bossGroup = new NioEventLoopGroup();
- EventLoopGroup workerGroup = new NioEventLoopGroup();
- try {
- ServerBootstrap b = new ServerBootstrap();
- b.group(bossGroup, workerGroup)
- .channel(NioServerSocketChannel.class)
- .option(ChannelOption.SO_BACKLOG, 1024)
- .childHandler(new ChildChannelHandler());
- ChannelFuture f = b.bind(port).sync();
- f.channel().closeFuture().sync();
- } finally {
- bossGroup.shutdownGracefully();
- workerGroup.shutdownGracefully();
- }
- protected MultithreadEventExecutorGroup(int nThreads, Executor executor, Object... args) {
- if (nThreads <= 0) {
- throw new IllegalArgumentException(String.format("nThreads: %d (expected: > 0)", nThreads));
- }
- if (executor == null) {
- executor = new ThreadPerTaskExecutor(newDefaultThreadFactory());
- }
- children = new EventExecutor[nThreads];
- for (int i = 0; i < nThreads; i ++) {
- boolean success = false;
- try {
- children[i] = newChild(executor, args);
- success = true;
- } catch (Exception e) {
- // TODO: Think about if this is a good exception type
- throw new IllegalStateException("failed to create a child event loop", e);
- } finally {
第二個概念是每個NioEventLoop都綁定了一個Selector,所以在Netty5的線程模型中,是由多個Selecotr在監聽IO就緒事件。而Channel注冊到Selector。
舉個例子,比如有100萬個連接連到服務器端。平時的寫法可能是1個Selector線程監聽所有的IO就緒事件,1個Selector面對100萬個連接(Channel)。
而如果使用了1000個NioEventLoop的線程池來說,1000個Selector面對100萬個連接,每個Selector只需要關注1000個連接(Channel)
- public final class NioEventLoop extends SingleThreadEventLoop {
- /**
- * The NIO {@link Selector}.
- */
- Selector selector;
- private SelectedSelectionKeySet selectedKeys;
- private final SelectorProvider provider;
第三個概念是一個Channel綁定一個NioEventLoop,相當於一個連接綁定一個線程,這個連接所有的ChannelHandler都是在一個線程中執行的,避免的多線程干擾。更重要的是ChannelPipline鏈表必須嚴格按照順序執行的。單線程的設計能夠保證ChannelHandler的順序執行。
- public interface Channel extends AttributeMap, Comparable<Channel> {
- /**
- * Return the {@link EventLoop} this {@link Channel} was registered too.
- */
- EventLoop eventLoop();
第四個概念是一個NioEventLoop的selector可以被多個Channel注冊,也就是說多個Channel共享一個EventLoop。EventLoop的Selecctor對這些Channel進行檢查。
這段代碼展示了線程池如何給Channel分配EventLoop,是根據Channel個數取模
- public EventExecutor next() {
- return children[Math.abs(childIndex.getAndIncrement() % children.length)];
- }
- private void processSelectedKeysOptimized(SelectionKey[] selectedKeys) {
- for (int i = 0;; i ++) {
- // 逐個處理注冊的Channel
- final SelectionKey k = selectedKeys[i];
- if (k == null) {
- break;
- }
- final Object a = k.attachment();
- if (a instanceof AbstractNioChannel) {
- processSelectedKey(k, (AbstractNioChannel) a);
- } else {
- @SuppressWarnings("unchecked")
- NioTask<SelectableChannel> task = (NioTask<SelectableChannel>) a;
- processSelectedKey(k, task);
- }
- if (needsToSelectAgain) {
- selectAgain();
- // Need to flip the optimized selectedKeys to get the right reference to the array
- // and reset the index to -1 which will then set to 0 on the for loop
- // to start over again.
- //
- // See https://github.com/netty/netty/issues/1523
- selectedKeys = this.selectedKeys.flip();
- i = -1;
- }
- }
- }
理解了這4個概念之后就對Netty5的線程模型有了清楚的認識:
在監聽一個端口的情況下,一個NioEventLoop通過一個NioServerSocketChannel監聽端口,處理TCP連接。后端多個工作線程NioEventLoop處理IO事件。每個Channel綁定一個NioEventLoop線程,1個NioEventLoop線程關聯一個selector來為多個注冊到它的Channel監聽IO就緒事件。NioEventLoop是單線程執行,保證Channel的pipline在單線程中執行,保證了ChannelHandler的執行順序。
下面這張圖來之http://blog.csdn.net/xiaolang85/article/details/37873059, 基本能說清楚。