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()); } }