RocketMQ源码分析(五)——Broker心跳原理
本章,我们来讲讲Broker是如何定时发送心跳到NameServer,让NameServer感知到Broker一直都存活着的。如果Broker一段时间内没有发送心跳到NameServer,那么NameServer是如何感知到Broker已经挂掉了呢?
一、心跳原理
首先,我们来回顾下BrokerController的启动,BrokerController启动的时候,其实并不是仅仅发送一次注册请求,而是启动了一个定时任务,会每隔一段时间就发送一次注册请求。
public void start() throws Exception {
//...忽略无关代码
// 启动一个定时调度任务,每隔一段时间进行一次注册,默认30s
this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
try {
BrokerController.this.registerBrokerAll(true, false, brokerConfig.isForceRegister());
} catch (Throwable e) {
log.error("registerBrokerAll Exception", e);
}
}
}, 1000 * 10, Math.max(10000, Math.min(brokerConfig.getRegisterNameServerPeriod(), 60000)), TimeUnit.MILLISECONDS);
//...忽略无关代码
}
我们通过上一章已经知道,第一次发送注册请求就是把Broker路由数据放入到NameServer的RouteInfoManager的路由数据表里去。
但是后续每隔30秒Broker都会发送一次注册请求,这些后续定时发送的注册请求本质就是Broker发送的心跳,那么,NameServer是如何处理这些后续重复发送过来的注册请求(心跳)呢?

1.1 RouteInfoManager
我们来看下RouteInfoManager
的注册方法registerBroker
的逻辑。下面的代码,有几个核心要点:
- Broker的路由信息全部维护在brokerAddrTable这个Map里面,然后Broker会以集群为维度被管理;
- 心跳机制的关键是用了一个brokerLiveTable管理Broker的最新心跳,它的key就是Broker,Value是BrokerLiveInfo对象。Broker每上送一次心跳,就会创建一个BrokerLiveInfo对象覆盖掉brokerLiveTable里面老的,BrokerLiveInfo里面有当前时间戳,表示最近一次心跳的时间。
public RegisterBrokerResult registerBroker(
final String clusterName,
final String brokerAddr,
final String brokerName,
final long brokerId,
final String haServerAddr,
final TopicConfigSerializeWrapper topicConfigWrapper,
final List<String> filterServerList,
final Channel channel) {
RegisterBrokerResult result = new RegisterBrokerResult();
try {
try {
// 加写锁,保证同一时刻只有一个线程能进行修改
this.lock.writeLock().lockInterruptibly();
// 根据clusterName获取这个集群下的Broker集合
Set<String> brokerNames = this.clusterAddrTable.get(clusterName);
if (null == brokerNames) {
brokerNames = new HashSet<String>();
this.clusterAddrTable.put(clusterName, brokerNames);
}
// 添加到集群
brokerNames.add(brokerName);
boolean registerFirst = false;
// Broker相关数据放在brokerAddrTable这个Map里,路由信息都在里面
BrokerData brokerData = this.brokerAddrTable.get(brokerName);
// 这里首次注册的情况
if (null == brokerData) {
registerFirst = true;
brokerData = new BrokerData(clusterName, brokerName, new HashMap<Long, String>());
this.brokerAddrTable.put(brokerName, brokerData);
}
// 对路由数据做处理,忽略
Map<Long, String> brokerAddrsMap = brokerData.getBrokerAddrs();
//Switch slave to master: first remove <1, IP:PORT> in namesrv, then add <0, IP:PORT>
//The same IP:PORT must only have one record in brokerAddrTable
Iterator<Entry<Long, String>> it = brokerAddrsMap.entrySet().iterator();
while (it.hasNext()) {
Entry<Long, String> item = it.next();
if (null != brokerAddr && brokerAddr.equals(item.getValue()) && brokerId != item.getKey()) {
it.remove();
}
}
String oldAddr = brokerData.getBrokerAddrs().put(brokerId, brokerAddr);
registerFirst = registerFirst || (null == oldAddr);
if (null != topicConfigWrapper
&& MixAll.MASTER_ID == brokerId) {
if (this.isBrokerTopicConfigChanged(brokerAddr, topicConfigWrapper.getDataVersion())
|| registerFirst) {
ConcurrentMap<String, TopicConfig> tcTable =
topicConfigWrapper.getTopicConfigTable();
if (tcTable != null) {
for (Map.Entry<String, TopicConfig> entry : tcTable.entrySet()) {
this.createAndUpdateQueueData(brokerName, entry.getValue());
}
}
}
}
// 这里是关键,Broker心跳管理:每次接受到心跳请求后,这里会封装一个BrokerLiveInfo,放到brokerLiveTable中,替换掉老的
// 这个BrokerLiveInfo里面,有一个当前时间戳,代表最近一次心跳的时间
BrokerLiveInfo prevBrokerLiveInfo = this.brokerLiveTable.put(brokerAddr,
new BrokerLiveInfo(
System.currentTimeMillis(),
topicConfigWrapper.getDataVersion(),
channel,
haServerAddr));
if (null == prevBrokerLiveInfo) {
log.info("new broker registered, {} HAServer: {}", brokerAddr, haServerAddr);
}
// 下面的代码忽略
if (filterServerList != null) {
if (filterServerList.isEmpty()) {
this.filterServerTable.remove(brokerAddr);
} else {
this.filterServerTable.put(brokerAddr, filterServerList);
}
}
if (MixAll.MASTER_ID != brokerId) {
String masterAddr = brokerData.getBrokerAddrs().get(MixAll.MASTER_ID);
if (masterAddr != null) {
BrokerLiveInfo brokerLiveInfo = this.brokerLiveTable.get(masterAddr);
if (brokerLiveInfo != null) {
result.setHaServerAddr(brokerLiveInfo.getHaServerAddr());
result.setMasterAddr(masterAddr);
}
}
}
} finally {
this.lock.writeLock().unlock();
}
} catch (Exception e) {
log.error("registerBroker Exception", e);
}
return result;
}
二、故障感知
了解了Broker的心跳机制,我们再来思考一个问题,如果当前的Broker挂掉了,NameServer是如何检测到的?
我们重新回到NamesrvController的initialize()
方法里去,里面启动了一个定时调度任务,调用RouteInfoManager的scanNotActiveBroker
方法去定时扫描不活跃的Broker。
public boolean initialize() {
this.kvConfigManager.load();
this.remotingServer = new NettyRemotingServer(this.nettyServerConfig, this.brokerHousekeepingService);
this.remotingExecutor =
Executors.newFixedThreadPool(nettyServerConfig.getServerWorkerThreads(), new ThreadFactoryImpl("RemotingExecutorThread_"));
this.registerProcessor();
// 后台定时任务,扫码不活跃的Broker
this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
NamesrvController.this.routeInfoManager.scanNotActiveBroker();
}
}, 5, 10, TimeUnit.SECONDS);
this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
NamesrvController.this.kvConfigManager.printAllPeriodically();
}
}, 1, 10, TimeUnit.MINUTES);
//...忽略无关代码
return true;
}
1.1 RouteInfoManager
我们来看下RouteInfoManager的scanNotActiveBroker方法:
public void scanNotActiveBroker() {
// 遍历brokerLiveTable
Iterator<Entry<String, BrokerLiveInfo>> it = this.brokerLiveTable.entrySet().iterator();
while (it.hasNext()) {
Entry<String, BrokerLiveInfo> next = it.next();
// 查看每个Broker的BrokerLiveInfo,也就是Broker的最新心跳时间
long last = next.getValue().getLastUpdateTimestamp();
// 如果心跳超时,就移除掉,默认120s
if ((last + BROKER_CHANNEL_EXPIRED_TIME) < System.currentTimeMillis()) {
// 断开与该超时Broker的连接
RemotingUtil.closeChannel(next.getValue().getChannel());
it.remove();
log.warn("The broker channel expired, {} {}ms", next.getKey(), BROKER_CHANNEL_EXPIRED_TIME);
this.onChannelDestroy(next.getKey(), next.getValue().getChannel());
}
}
}
该方法很简单,就是遍历brokerLiveTable,找到那些超过120s(默认)还没发送心跳的Broker,将它们移除,同时断开连接。
三、总结
本章,我们讲解了Broker的心跳机制,本质就是NameServer中的RouteInfoManager组件对其中的Broker路由信息的管理。
感谢赞赏~