懂得
1级
2017-05-14 回答
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的注释)
[java] view plain copy
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());
}
}