zoukankan      html  css  js  c++  java
  • netty的心跳检测实现

    由于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); 
        }

  • 相关阅读:
    C#读写设置修改调整UVC摄像头画面-曝光
    C#读写调整修改设置UVC摄像头画面-逆光对比
    C#读写修改设置调整UVC摄像头画面-清晰度
    C#读写设置修改调整UVC摄像头画面-对比度
    C#读写调整设置UVC摄像头画面-亮度
    C#采集UVC摄像头画面并支持旋转和分辨率切换
    一张图看懂SharpCamera
    C#混音同时录制采集声卡和麦克风话筒
    C#采集麦克风话筒声音
    Windows下安装Redis服务
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13318012.html
Copyright © 2011-2022 走看看