前言
前面我们介绍了Broker每隔30s会向Namesrv发送心跳包,心跳包中包含Broker路由信息,Namesrv会更新RouteInfoManager中的路由信息。如果Broker宕机,Namesrv是如何判断Broker不可用,并将broker从路由信息中剔除的呢?
路由失效源码分析
NamesrvController初始化会启动定时线程池,其中就包括扫描不健康Broker的schedule线程池。NamesrvController启动时会调用NamesrvController#startScheduleService
,启动namesrv中的定时任务,其中就包括检查不健康Broker的schedule线程池。
private void startScheduleService() {
// 每5秒检测一次不健康的broker
this.scanExecutorService.scheduleAtFixedRate(NamesrvController.this.routeInfoManager::scanNotActiveBroker,
5, this.namesrvConfig.getScanNotActiveBrokerInterval()/*默认5s*/, TimeUnit.MILLISECONDS);
}
复制代码
在定时任务中遍历brokerLiveTable,如果当前时间大于broker最后更新时间+超时时间(默认是120s),也就是说namesrv距离最后一次收到broker的心跳已经超过了120s。namesrv会主动关闭与broker的channel,并且发送broker注销请求。
public void scanNotActiveBroker() {
try {
log.info("start scanNotActiveBroker");
// 遍历存活brokerTable
for (Entry<BrokerAddrInfo, BrokerLiveInfo> next : this.brokerLiveTable.entrySet()) {
long last = next.getValue().getLastUpdateTimestamp();
long timeoutMillis = next.getValue().getHeartbeatTimeoutMillis();
if ((last + timeoutMillis) < System.currentTimeMillis()) {
// 关闭channel
RemotingHelper.closeChannel(next.getValue()/*BrokerLiveInfo*/.getChannel());
log.warn("The broker channel expired, {} {}ms", next.getKey(), timeoutMillis);
// 发送broker注销请求
this.on