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

看下面代码:
[java] view plaincopy
- EventLoopGroup group = new NioEventLoopGroup();
- Bootstrap bootstrap = new Bootstrap();
- bootstrap.group(group).channel(NioSocketChannel.class)
- .handler(new SimpleChannelInboundHandler<ByteBuf>() {
- @Override
- protected void channelRead0(ChannelHandlerContext ctx,
- ByteBuf msg) throws Exception {
- //remove this ChannelHandler and de-register
- ctx.pipeline().remove(this);
- ctx.deregister();
- }
- });
- ChannelFuture future = bootstrap.connect(
- new InetSocketAddress("www.baidu.com", 80)).sync();
- //....
- Channel channel = future.channel();
- //re-register channel and add ChannelFutureLister
- group.register(channel).addListener(new ChannelFutureListener() {
- @Override
- public void operationComplete(ChannelFuture future) throws Exception {
- if(future.isSuccess()){
- System.out.println("Channel registered");
- }else{
- System.out.println("register channel on EventLoop fail");
- future.cause().printStackTrace();
- }
- }
- });