netty 优雅关闭

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

  • 9
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值