前言
在RocketMQ
中为,我们创建消息生产者时,只需要设置NameServer
地址,消息就能正确地发送到对应的Broker
中,那么RocketMQ
消息生产者是如何找到Broker
的呢?如果有多个Broker
实例,那么消息发送是如何选择发送到哪个Broker
的呢?
从NameServer查询Topic信息
通过Debug消息发送send()
方法,我们最终可以定位到DefaultMQProducerImpl.sendDefaultImpl()
这个方法,并且我们找到了最关键的Topic信息:
TopicPublishInfo topicPublishInfo = this.tryToFindTopicPublishInfo(msg.getTopic());
复制代码
这个方法就是通过topic
从NameServer
拉出对应的Broker
信息:
private TopicPublishInfo tryToFindTopicPublishInfo(final String topic) {
TopicPublishInfo topicPublishInfo = this.topicPublishInfoTable.get(topic);
if (null == topicPublishInfo || !topicPublishInfo.ok()) {
this.topicPublishInfoTable.putIfAbsent(topic, new TopicPublishInfo());
this.mQClientFactory.updateTopicRouteInfoFromNameServer(topic);
topicPublishInfo = this.topicPublishInfoTable.get(topic);
}
if (topicPublishInfo.isHaveTopicRouterInfo() || topicPublishInfo.ok()) {
return topicPublishInfo;
} else {
this.mQClientFactory.updateTopicRouteInfoFromNameServer(topic, true, this.defaultMQProducer);
topicPublishInfo = this.topicPublishInfoTable.get(topic);
return topicPublishInfo;
}
}
复制代码