源码分析RocketMQ消息PULL-长轮询模式

RemotingCommand request,

boolean brokerAllowSuspend)

  • Channel channel:网络通道

  • RemotingCommand request:消息拉取请求

  • brokerAllowSuspend:是否允许挂起,也就是是否允许在未找到消息时暂时挂起线程。第一次调用时默认为true。

case ResponseCode.PULL_NOT_FOUND:

if (brokerAllowSuspend && hasSuspendFlag) { // @1

long pollingTimeMills = suspendTimeoutMillisLong; // @2

if (!this.brokerController.getBrokerConfig().isLongPollingEnable()) { // @3

pollingTimeMills = this.brokerController.getBrokerConfig().getShortPollingTimeMills();

}

String topic = requestHeader.getTopic();

long offset = requestHeader.getQueueOffset();

int queueId = requestHeader.getQueueId();

PullRequest pullRequest = new PullRequest(request, channel, pollingTimeMills,

this.brokerController.getMessageStore().now(), offset, subscriptionData, messageFilter); // @4

this.brokerController.getPullRequestHoldService().suspendPullRequest(topic, queueId, pullRequest);

response = null; // @5

break;

}

代码@1:hasSuspendFlag, 构建消息拉取时的拉取标记,默认为true。

代码@2:suspendTimeoutMillisLong:取自 DefaultMQPullConsumer 的 brokerSuspendMaxTimeMillis属性。

代码@3:如果不支持长轮询,则忽略 brokerSuspendMaxTimeMillis 属性,使用 shortPollingTimeMills,默认为1000ms作为下一次拉取消息的等待时间。

代码@4:创建 PullRequest, 然后提交给 PullRequestHoldService 线程去调度,触发消息拉取。

代码@5:关键,设置response=null,则此时此次调用不会向客户端输出任何字节,客户端网络请求客户端的读事件不会触发,不会触发对响应结果的处理,处于等待状态。

在拉取消息时,如果拉取结果为 PULL_NOT_FOUND,在服务端默认会挂起线程,然后根据是否启用长轮询机制,延迟一定时间后再次重试根据偏移量查找消息。

再研究轮询查找消息之前先看一下PullRequest对象的核心属性:

这里写图片描述

  • requestCommand:请求命令

  • clientChannel:网络连接,通过该通道向客户端返回响应结果。

  • timeoutMills:超时时长

  • suspendTimestamp:挂起开始时间戳,如果当前系统>=(timeoutMills+suspendTimestamp)表示已超时。

  • pullFromThisOffset:带拉取消息队列偏移量

  • subscriptionData:订阅信息。

  • messageFilter:消息过滤器

RocketMQ轮询机制由两个线程共同来完成:

  • PullRequestHoldService:每隔5S重试一次。

  • DefaultMessageStore#ReputMessageService,每处理一次重新拉取,Thread.sleep(1),继续下一次检查。

3、源码分析PullRequestHoldService线程


3.1 PullRequestHoldService#suspendPullRequest

public void suspendPullRequest(final String topic, final int queueId, final PullRequest pullRequest) {

String key = this.buildKey(topic, queueId);

ManyPullRequest mpr = this.pullRequestTable.get(key);

if (null == mpr) {

mpr = new ManyPullRequest();

ManyPullRequest prev = this.pullRequestTable.putIfAbsent(key, mpr);

if (prev != null) {

mpr = prev;

}

}

mpr.addPullRequest(pullRequest);

}

根据主题名称 + 队列id, 获取 ManyPullRequest, 对于同一个 topic + 队列的拉取请求用 ManyPullRequest包装,然后将 pullRequest 添加到 ManyPullRequest 中。

3.2 run方法详解

PullRequestHoldService#run

public void run() {

log.info(“{} service started”, this.getServiceName());

while (!this.isStopped()) {

try {

if (this.brokerController.getBrokerConfig().isLongPollingEnable()) {

this.waitForRunning(5 * 1000); // @1

} else {

this.waitForRunning(this.brokerController.getBrokerConfig().getShortPollingTimeMills()); //@2

}

long beginLockTimestamp = this.systemClock.now();

this.checkHoldRequest(); // @3

long costTime = this.systemClock.now() - beginLockTimestamp;

if (costTime > 5 * 1000) {

log.info(“[NOTIFYME] check hold request cost {} ms.”, costTime);

}

} catch (Throwable e) {

log.warn(this.getServiceName() + " service has exception. ", e);

}

}

log.info(“{} service end”, this.getServiceName());

}

代码@1:如果开启了长轮询模式,则每次只挂起 5s,然后就去尝试拉取。

代码@2:如果不开启长轮询模式,则只挂起一次,挂起时间为 shortPollingTimeMills,然后去尝试查找消息。

代码@3:遍历 pullRequestTable,如果拉取任务的待拉取偏移量小于当前队列的最大偏移量时执行拉取,否则如果没有超过最大等待时间则等待,否则返回未拉取到消息,返回给消息拉取客户端。具体请看:

PullRequestHoldService#checkHoldRequest。

private void checkHoldRequest() {

for (String key : this.pullRequestTable.keySet()) {

String[] kArray = key.split(TOPIC_QUEUEID_SEPARATOR);

if (2 == kArray.length) {

String topic = kArray[0];

int queueId = Integer.parseInt(kArray[1]);

final long offset = this.brokerController.getMessageStore().getMaxOffsetInQueue(topic, queueId); // @1

try {

this.notifyMessageArriving(topic, queueId, offset); // @2

} catch (Throwable e) {

log.error(“check hold request failed. topic={}, queueId={}”, topic, queueId, e);

}

}

}

}

代码@1:根据主题,消费队列ID查找队列的最大偏移量。

代码@2:根据该offset,判断是否有新的消息达到。

PullRequestHoldService#notifyMessageArriving

public void notifyMessageArriving(final String topic, final int queueId, final long maxOffset, final Long tagsCode,

long msgStoreTime, byte[] filterBitMap, Map<String, String> properties) { // @1

String key = this.buildKey(topic, queueId);

ManyPullRequest mpr = this.pullRequestTable.get(key);

if (mpr != null) {

List requestList = mpr.cloneListAndClear(); // @2

if (requestList != null) {

List replayList = new ArrayList();

for (PullRequest request : requestList) {

long newestOffset = maxOffset;

if (newestOffset <= request.getPullFromThisOffset()) { // @3

newestOffset = this.brokerController.getMessageStore().getMaxOffsetInQueue(topic, queueId);

}

if (newestOffset > request.getPullFromThisOffset()) { // @4

boolean match = request.getMessageFilter().isMatchedByConsumeQueue(tagsCode,

new ConsumeQueueExt.CqExtUnit(tagsCode, msgStoreTime, filterBitMap));

// match by bit map, need eval again when properties is not null.

if (match && properties != null) {

match = request.getMessageFilter().isMatchedByCommitLog(null, properties);

}

if (match) {

try {

this.brokerController.getPullMessageProcessor().executeRequestWhenWakeup(request.getClientChannel(),

request.getRequestCommand());

} catch (Throwable e) {

log.error(“execute request when wakeup failed.”, e);

}

continue;

}

}

if (System.currentTimeMillis() >= (request.getSuspendTimestamp() + request.getTimeoutMillis())) { // @5

try {

this.brokerController.getPullMessageProcessor().executeRequestWhenWakeup(request.getClientChannel(),

request.getRequestCommand());

} catch (Throwable e) {

log.error(“execute request when wakeup failed.”, e);

}

continue;

}

replayList.add(request);

}

if (!replayList.isEmpty()) {

mpr.addPullRequest(replayList); // @6

}

}

}

}

代码@1:参数详解:

  • String topic:主题名称。

  • int queueId:队列id。

  • long maxOffset:消费队列当前最大偏移量。

  • Long tagsCode:消息tag hashcode //基于tag消息过滤。

  • long msgStoreTime:消息存储时间。

  • byte[] filterBitMap:过滤位图。

  • Map<String, String> properties:消息属性,基于属性的消息过滤。

代码@2:获取主题与队列的所有 PullRequest 并清除内部 pullRequest 集合,避免重复拉取。

代码@3:如果待拉取偏移量(pullFromThisOffset)大于消息队列的最大有效偏移量,则再次获取消息队列的最大有效偏移量,再给一次机会。

代码@4:如果队列最大偏移量大于 pullFromThisOffset 说明有新的消息到达,先简单对消息根据 tag,属性进行一次消息过滤,如果 tag,属性为空,则消息过滤器会返回true,然后 executeRequestWhenWakeup进行消息拉取,结束长轮询。

代码@5:如果挂起时间超过 suspendTimeoutMillisLong,则超时,结束长轮询,调用executeRequestWhenWakeup 进行消息拉取,并返回结果到客户端。

代码@6:如果待拉取偏移量大于消息消费队列最大偏移量,并且未超时,调用 mpr.addPullRequest(replayList) 将拉取任务重新放入,待下一次检测。

ManyPullRequest#addPullRequest

public synchronized void addPullRequest(final List many) {

this.pullRequestList.addAll(many);

}

这个方法值得注意一下,为什么 addPullRequest 方法会加锁呢?原因是 ReputMessageService 内部其实会持有 PullRequestHoldService 的引用,也就是在运行过程中,对于拉取任务, ReputMessageService、PullRequestHoldService处理的任务是同一个集合。

继续代码@5:重点跟进一下 executeRequestWhenWakeup 方法。

PullMessageProcessor#executeRequestWhenWakeup

public void executeRequestWhenWakeup(final Channel channel,

final RemotingCommand request) throws RemotingCommandException {

Runnable run = new Runnable() {

@Override

public void run() {

try {

final RemotingCommand response = PullMessageProcessor.this.processRequest(channel, request, false);

if (response != null) {

response.setOpaque(request.getOpaque());

response.markResponseType();

try {

channel.writeAndFlush(response).addListener(new ChannelFutureListener() {

@Override

public void operationComplete(ChannelFuture future) throws Exception {

if (!future.isSuccess()) {

log.error(“processRequestWrapper response to {} failed”,

future.channel().remoteAddress(), future.cause());

log.error(request.toString());

log.error(response.toString());

}

}

});

} catch (Throwable e) {

log.error(“processRequestWrapper process request over, but response failed”, e);

log.error(request.toString());

log.error(response.toString());

}

}

} catch (RemotingCommandException e1) {

log.error(“excuteRequestWhenWakeup run”, e1);

}

}

};

this.brokerController.getPullMessageExecutor().submit(new RequestTask(run, channel, request));

}

这里的核心亮点是:在调用 PullMessageProcessor.this.processRequest(channel, request, false) 方法是,最后一个参数是 false,表示 broker 端不支持挂起,这样在 PullMessageProcessor 方法中,如果没有查找消息,也不会继续再挂起了,因为进入这个方法时,拉取的偏移量是小于队列的最大偏移量,正常情况下是可以拉取到消息的。

4、源码分析DefaultMessageStore#ReputMessageService


ReputMessageService启动入口:DefaultMessageStore#satart方法:

if (this.getMessageStoreConfig().isDuplicationEnable()) {

this.reputMessageService.setReputFromOffset(this.commitLog.getConfirmOffset());

} else {

this.reputMessageService.setReputFromOffset(this.commitLog.getMaxOffset());

}

this.reputMessageService.start();

首先,设置 reputFromOffset 偏移量,如果允许重复,初始偏移量为 confirmOffset,否则设置为commitLog 当前最大偏移量。

4.1 run方法

public void run() {

DefaultMessageStore.log.info(this.getServiceName() + " service started");

while (!this.isStopped()) {

try {

Thread.sleep(1);

this.doReput();

} catch (Exception e) {

DefaultMessageStore.log.warn(this.getServiceName() + " service has exception. ", e);

}

}

DefaultMessageStore.log.info(this.getServiceName() + " service end");

}

从 run 方法可以看出 ReputMessageService 线程是一个“拼命三郎”,每执行完一次业务方法 doReput,休息1毫秒,就继续抢占CPU,再次执行 doReput 方法。
自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数Java工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则几千的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年Java开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Java开发知识点,真正体系化!

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!

如果你觉得这些内容对你有帮助,可以扫码获取!!(备注Java获取)

img

复习的面试资料

这些面试全部出自大厂面试真题和面试合集当中,小编已经为大家整理完毕(PDF版)

  • 第一部分:Java基础-中级-高级

image

  • 第二部分:开源框架(SSM:Spring+SpringMVC+MyBatis)

image

  • 第三部分:性能调优(JVM+MySQL+Tomcat)

image

  • 第四部分:分布式(限流:ZK+Nginx;缓存:Redis+MongoDB+Memcached;通讯:MQ+kafka)

image

  • 第五部分:微服务(SpringBoot+SpringCloud+Dubbo)

image

  • 第六部分:其他:并发编程+设计模式+数据结构与算法+网络

image

进阶学习笔记pdf

  • Java架构进阶之架构筑基篇(Java基础+并发编程+JVM+MySQL+Tomcat+网络+数据结构与算法

image

  • Java架构进阶之开源框架篇(设计模式+Spring+SpringMVC+MyBatis

image

image

image

  • Java架构进阶之分布式架构篇 (限流(ZK/Nginx)+缓存(Redis/MongoDB/Memcached)+通讯(MQ/kafka)

image

image

image

  • Java架构进阶之微服务架构篇(RPC+SpringBoot+SpringCloud+Dubbo+K8s)

image

image

《互联网大厂面试真题解析、进阶开发核心学习笔记、全套讲解视频、实战项目源码讲义》点击传送门即可获取!
va架构进阶之开源框架篇(设计模式+Spring+SpringMVC+MyBatis)**

[外链图片转存中…(img-TbgBfIhu-1713751354128)]

[外链图片转存中…(img-L57iPTC2-1713751354128)]

[外链图片转存中…(img-RNOXoEGX-1713751354128)]

  • Java架构进阶之分布式架构篇 (限流(ZK/Nginx)+缓存(Redis/MongoDB/Memcached)+通讯(MQ/kafka)

[外链图片转存中…(img-idoiOArk-1713751354128)]

[外链图片转存中…(img-J5EXzbtL-1713751354129)]

[外链图片转存中…(img-nAUcVpVB-1713751354129)]

  • Java架构进阶之微服务架构篇(RPC+SpringBoot+SpringCloud+Dubbo+K8s)

[外链图片转存中…(img-epkKkW3Z-1713751354129)]

[外链图片转存中…(img-q4HByhuL-1713751354129)]

《互联网大厂面试真题解析、进阶开发核心学习笔记、全套讲解视频、实战项目源码讲义》点击传送门即可获取!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值