Dubbo默认客户端和服务器端都会发送心跳报文,用来保持TCP长连接状态。在客户端和服务端,Dubbo内部开启一个线程循环扫描并检测连接是否超时,在服务端如果发现超时则会主动关闭客户端连接,在客户端发现超时则会主动重新创建连接。默认心跳检测60s,具体应用可以通过heartbeat配置
Dubbo在服务端和客户端都复用心跳实现代码,抽象成HeartBeatTask任务进行处理
@Override
public void run(){
try{
long now = Systtem.currentTimeMillis();
for(Channel channel : channelProvider.getChannels()){
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{
((Client)channel).reconnect();
}catch(Exception e){}
}else{
channel.close();
}
}
}
}
}
}
|