Netty5源碼分析(二) -- 執行緒模式分析

來源:互聯網
上載者:User

執行緒模式是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, 基本能說清楚。




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.