netty的心跳检测实现

分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.csdn.net/jiangjunshow

也欢迎大家转载本篇文章。分享知识,造福人民,实现我们中华民族伟大复兴!

               
由于netty采用了事件机制,因此给链路监测和连接管理带来了一些麻烦,因此最好给链路加上心跳处理(1) 服务器端关键点,主要在initpipe中和实现IdleStateAwareChannelHandler.         pipeline.addLast("timeout", new IdleStateHandler(timer, 10, 10, 0));//此两项为添加心跳机制 10秒查看一次在线的客户端channel是否空闲,IdleStateHandler为netty jar包中提供的类          pipeline.addLast("hearbeat", new Heartbeat());如果要捕获检测结果,需要继承IdleStateAwareChannelHandler,来判断客户端是否存在,但是这种机制还得一个心跳包发送来检测。public class Heartbeat extends IdleStateAwareChannelHandler{  int i = 0;  @Override public void channelIdle(ChannelHandlerContext ctx, IdleStateEvent e)   throws Exception // TODO Auto-generated method stub  super.channelIdle(ctx, e);    if(e.getState() == IdleState.WRITER_IDLE)   i++;    if(i==3){   e.getChannel().close();      System.out.println("掉了。");  } } }(2)客户端关键点,也在booststrap,initpipe和IdleStateAwareChannelHandler        bootstrap.setOption("allIdleTime","5"); //这里,很重要        pipeline.addLast("timeout", new IdleStateHandler(timer, 0, 0, 10));        pipeline.addLast("idleHandler", new ClientIdleHandler());              实现IdleStateAwareChannelHandler 的handler负责定时发送检测包public class ClientIdleHandler extends IdleStateAwareChannelHandler {    final Logger logger = LoggerFactory.getLogger(ClientIdleHandler.class);    @Override    public void channelIdle(ChannelHandlerContext ctx, IdleStateEvent e) throws Exception {    if( e.getState() == IdleState.ALL_IDLE){            logger.debug("链路空闲!发送心跳!S:{} - C:{} idleState:{}", new Object[]{ctx.getChannel().getRemoteAddress(), ctx.getChannel().getLocalAddress() , e.getState()});            e.getChannel().write(MessageHelper.buildMessageEcho());            super.channelIdle(ctx, e);             }    }}此外为了获得一些业务阻塞异常导致一些网路不确认状态,采取办法是:用发送upstream的异常来通知解决。    public void exceptionCaught(             ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {         if (this == ctx.getPipeline().getLast()) {             logger.warn(                     "EXCEPTION, please implement " + getClass().getName() +                     ".exceptionCaught() for proper handling.", e.getCause());         }         ctx.sendUpstream(e);     }

           

给我老师的人工智能教程打call!http://blog.csdn.net/jiangjunshow

这里写图片描述

猜你喜欢

转载自blog.csdn.net/yrryyff/article/details/83760116