netty入门学习(5)-超时处理

来源:互联网 发布:淘宝秧歌服在哪儿买 编辑:程序博客网 时间:2024/05/20 00:13

服务端和客户端同时增加如下代码:

Timer trigger=new HashedWheelTimer();final ChannelHandler timeOutHandler=new ReadTimeoutHandler(trigger,60);//final ChannelHandler idleStateHandler=new IdleStateHandler(trigger,60,5,0);//设置处理客户端消息和各种消息事件的类(Handler)bootstrap.setPipelineFactory(new ChannelPipelineFactory(){@Overridepublic ChannelPipeline getPipeline() throws Exception {return Channels.pipeline(timeOutHandler,new LengthFieldPrepender(2),new LengthFieldBasedFrameDecoder(64*1024,0,2,0,2),new BusinessHandler());}});

如果设置了ReadTimeoutHandler这个Handler,且间隔60S未读数据,则会抛出一个ReadTimeoutException,默认情况下不会影响数据发送。

因为NIO是异步处理,所以客户端得到响应可以关闭channel,但服务端并不能明确知晓何时关闭clientChannel,所以常用的策略就是捕获超时异常(后面还有心跳机制等)共同处理 clientChannel的关闭问题。


超时也可以使用idleStateHandler,idleStateHandler提供了读超时,写超时,读写混合超时的处理策略,与ReadTimeOutHandler不同的,idleStatehandler以向后传递空闲事件的方式来处理超时,如果使用idleStateHandler一般配合使用IdleStateAwareChannelHandler来捕获状态进行处理。

Timer trigger=new HashedWheelTimer();final ChannelHandler timeOutHandler=new ReadTimeoutHandler(trigger,60);final ChannelHandler idleStateHandler=new IdleStateHandler(trigger,60,5,0);        // 设置一个处理服务端消息和各种消息事件的类(Handler)        bootstrap.setPipelineFactory(new ChannelPipelineFactory() {            @Override            public ChannelPipeline getPipeline() throws Exception {                return Channels.pipeline(timeOutHandler,                idleStateHandler,                new SocketLinkState(),                new LengthFieldPrepender(2),                new LengthFieldBasedFrameDecoder(64*1024,0,2,0,2),                new RequestHandler());            }        });

private static class SocketLinkState extends IdleStateAwareChannelHandler{  @Override  public void exceptionCaught(ChannelHandlerContext ctx,ExceptionEvent e) throws Exception{    // JavaUtil.callLevels();    Throwable throwed=e.getCause();    throwed.printStackTrace();    // throwed.printStackTrace(System.err);    if(throwed instanceof ReadTimeoutException){      ctx.getChannel().close();    }    else if(throwed instanceof IOException){      ctx.getChannel().close();    }    else{      super.exceptionCaught(ctx,e);    }  }    @Override  public void channelIdle(//  ChannelHandlerContext ctx,//  IdleStateEvent e) throws Exception{    super.channelIdle(ctx,e);    Channel channel=e.getChannel();    switch(e.getState()){      case READER_IDLE: {// 读取时间超时        // e.getChannel().close();// 关闭网络连接        // new RuntimeException().printStackTrace();        break;      }      case WRITER_IDLE: {// 读取时间超时        SocketHeartBeat.sendHeartBeat(channel);        break;      }    }  }}

ReadTimeOutHandler的作用是读超时时向后传递异常

idleStatehandler的作用是读超时或写超时向后传递空闲事件

SocketLinkState是对ReadTimeOutHandler和idleStatehandler进行处理,对ReadTimeOutHandler抛出的异常在exceptionCaught中进行处理,并关闭channel,channelIdle则是捕获住相关事件进行处理,在本例中,未对读超时进行处理,因为在ReadTimeOutHandler已经进行处理了。针对写超时,采用心跳机制唤醒。

心跳机制在下节中讨论。


原创粉丝点击