Dubbo心跳逻辑处理

Dubbo默认客户端和服务器端都会发送心跳报文,用来保持TCP长连接状态。在客户端和服务端,Dubbo内部开启一个线程循环扫描并检测连接是否超时,在服务端如果发现超时则会主动关闭客户端连接,在客户端发现超时则会主动重新创建连接。默认心跳检测60s,具体应用可以通过heartbeat配置

Dubbo在服务端和客户端都复用心跳实现代码,抽象成HeartBeatTask任务进行处理

@Override
public void run(){
  try{
    long now = Systtem.currentTimeMillis();
    //遍历所有的channel
    for(Channel channel : channelProvider.getChannels()){
      //忽略掉关闭的channel
      if(channel.isClosed()){
        continue;
      }
      try{
        long lastRead = (Long)channel.getAttribute(HeadeeExchangeHandler.KEY_READ_TIMESTAMP);
        long lastWrite = (Long)channel.getAttribute(HeaderExchangeHandler.KEY_WRITE_TIMESTAMP);
        if((lastRead != null && now - lastRead > heartBeat)||(lastWrite != null && now - lastWrite > heartBeat)){
          Request req = new Request();
          req.setVersion(Version.getProtocolVersion());
          req.setTwoWay(true);
          req.setEvent(Request.HEARTBEAT_EVENT);
          channel.send(req);
          if(logger.isDubugEnabled()){
            logger.debug("aaaaxxx");
          }
        }
        if(lastRead != null && now - lastRead > heartbeatTimeout){
          logger.warn("Close channel"+channel);
          if(channel instanceof Client){
            try{
              //客户端空闲超时触发重连,默认超市3分钟
              ((Client)channel).reconnect();
            }catch(Exception e){}
          }else{
            //服务端关闭连接
            channel.close();
          }
        }
      }
    }
  }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值