netty 優雅關閉

來源:互聯網
上載者:User

       netty是一個java nio的網路架構,它屏蔽了底層網路細節,並且非常的高效。如果你是最近要開發一個訊息平台,使用netty最好不過了。

       一個好的訊息平台有很多需要注意的細節和應該遵守的約定準則。其中平台的優雅關閉必不可少。這個主要是避免訊息丟失。那麼如何做到netty的優雅關閉呢?

       在netty中,接受串連請求和對請求進行業務處理分別有兩個線程執行器bossExecutor 和 workerExecutor,除了關閉這兩個外還需要關閉channel。

        netty文檔說優雅關閉需要三步:

        1. unbind netty建立的所有channel。channel.unbind()

        2. close netty建立的所有channel。channel.close()

        3. shutdown netty的線程執行器。factory.releaseExternalResources()

       對於netty產生的channel,可以使用ChannelGroup管理,很方便。

       具體的代碼如下:(可以參看ChannelGroup的注釋)

       

 ChannelGroup allChannels = new DefaultChannelGroup(); public static void main(String[] args) throws Exception {     ServerBootstrap b = new ServerBootstrap(..);     ...     // Start the server     b.getPipeline().addLast("handler", new MyHandler());     Channel serverChannel = b.bind(..);     allChannels.add(serverChannel);     ... Wait until the shutdown signal reception ...     // Close the serverChannel and then all accepted connections.     allChannels.close().awaitUninterruptibly();     b.releaseExternalResources(); } public class MyHandler extends SimpleChannelUpstreamHandler {     @Override     public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) {         // Add all open channels to the global group so that they are         // closed on shutdown.         allChannels.add(e.getChannel());     } }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.