16.2 挂起IO处理

    在一些情况下可能需要停止一个指定通道的处理操作,比如程序耗尽内存、崩溃、失去一些消息,此时,我们可以停止处理事件的通道来清理系统资源,以保持程序稳定继续处理后续消息。若这样做,最好的方式就是从EventLoop取消注册的通道,这可以有效阻止通道再处理任何事件。若需要被取消的通道再次处理事件,则只需要将该通道重新注册到EventLooop即可。看下图:

http://img.blog.csdn.net/20140811142451139?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvYWJjX2tleQ==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast

看下面代码:

[java] view plaincopy在CODE上查看代码片

  1. EventLoopGroup group = new NioEventLoopGroup();
  2. Bootstrap bootstrap = new Bootstrap();
  3. bootstrap.group(group).channel(NioSocketChannel.class)
  4. .handler(new SimpleChannelInboundHandler<ByteBuf>() {
  5. @Override
  6. protected void channelRead0(ChannelHandlerContext ctx,
  7. ByteBuf msg) throws Exception {
  8. //remove this ChannelHandler and de-register
  9. ctx.pipeline().remove(this);
  10. ctx.deregister();
  11. }
  12. });
  13. ChannelFuture future = bootstrap.connect(
  14. new InetSocketAddress("www.baidu.com", 80)).sync();
  15. //....
  16. Channel channel = future.channel();
  17. //re-register channel and add ChannelFutureLister
  18. group.register(channel).addListener(new ChannelFutureListener() {
  19. @Override
  20. public void operationComplete(ChannelFuture future) throws Exception {
  21. if(future.isSuccess()){
  22. System.out.println("Channel registered");
  23. }else{
  24. System.out.println("register channel on EventLoop fail");
  25. future.cause().printStackTrace();
  26. }
  27. }
  28. });

results matching ""

    No results matching ""