RocketMQ源码解析十(定时消息(延时消息)流程)

朴灿烈づ我的快乐病毒、 2022-09-12 07:47 157阅读 0赞

RocketMQ版本4.6.0,记录自己看源码的过程

定时消息是指消息发送到Broker后,并不立即被消费者消费而是要等到特定的时间后才能被消费,RocketMQ不支持任意的时间精度。
发送消息时,只要给消息设置一个延时级别message.setDelayTimeLevel(3),消息发送到Broker后会延时固定时间后才可以被消费到。
延时有一下几个级别:

  1. private String messageDelayLevel = "1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h";

从1s到2h分别对应着等级1到18。除了主动设置延时消息,消息消费失败也会进入延时消息队列,所以消息发送时间与设置的延时等级和重试次数有关。

Broker接收定时消息前半段处理跟普通消息一样,但在CommitLog中准备去存储消息时处理不大一样
CommitLog

  1. public PutMessageResult putMessage(final MessageExtBrokerInner msg) {
  2. // Set the storage time
  3. msg.setStoreTimestamp(System.currentTimeMillis());
  4. // Set the message body BODY CRC (consider the most appropriate setting
  5. // on the client)
  6. msg.setBodyCRC(UtilAll.crc32(msg.getBody()));
  7. // Back to Results
  8. AppendMessageResult result = null;
  9. StoreStatsService storeStatsService = this.defaultMessageStore.getStoreStatsService();
  10. String topic = msg.getTopic();
  11. int queueId = msg.getQueueId();
  12. final int tranType = MessageSysFlag.getTransactionValue(msg.getSysFlag());
  13. if (tranType == MessageSysFlag.TRANSACTION_NOT_TYPE
  14. || tranType == MessageSysFlag.TRANSACTION_COMMIT_TYPE) {
  15. // 延时消息,则改变主题
  16. if (msg.getDelayTimeLevel() > 0) {
  17. // 超过最大延时级别则设为最大延时级别
  18. if (msg.getDelayTimeLevel() > this.defaultMessageStore.getScheduleMessageService().getMaxDelayLevel()) {
  19. msg.setDelayTimeLevel(this.defaultMessageStore.getScheduleMessageService().getMaxDelayLevel());
  20. }
  21. // topic设为SCHEDULE_TOPIC_XXXX
  22. topic = ScheduleMessageService.SCHEDULE_TOPIC;
  23. // 队列id = 延时级别-1
  24. queueId = ScheduleMessageService.delayLevel2QueueId(msg.getDelayTimeLevel());
  25. // 备份真实主题和队列id,REAL_TOPIC为延时之前的topic,REAL_QID为延时之前的queueId
  26. MessageAccessor.putProperty(msg, MessageConst.PROPERTY_REAL_TOPIC, msg.getTopic());
  27. MessageAccessor.putProperty(msg, MessageConst.PROPERTY_REAL_QUEUE_ID, String.valueOf(msg.getQueueId()));
  28. msg.setPropertiesString(MessageDecoder.messageProperties2String(msg.getProperties()));
  29. // 延迟消息则需要将消息发送到延时主题上
  30. msg.setTopic(topic);
  31. msg.setQueueId(queueId);
  32. }
  33. }
  34. // 后面省略,跟普通消息处理一样
  35. }

随后的处理方式跟普通消息一样,存入CommitLog文件。
然后后台会有一个定时消息服务ScheduleMessageService,该服务会消息存储组件一起创建、加载和启动
ScheduleMessageService

  1. public class ScheduleMessageService extends ConfigManager {
  2. private static final InternalLogger log = InternalLoggerFactory.getLogger(LoggerName.STORE_LOGGER_NAME);
  3. public static final String SCHEDULE_TOPIC = "SCHEDULE_TOPIC_XXXX";
  4. private static final long FIRST_DELAY_TIME = 1000L;
  5. private static final long DELAY_FOR_A_WHILE = 100L;
  6. private static final long DELAY_FOR_A_PERIOD = 10000L;
  7. /** * 延时级别表,key时延时级别,value是延时时间 */
  8. private final ConcurrentMap<Integer /* level */, Long/* delay timeMillis */> delayLevelTable =
  9. new ConcurrentHashMap<Integer, Long>(32);
  10. /** * 缓存每个延时级别对应队列的消费进度 */
  11. private final ConcurrentMap<Integer /* level */, Long/* offset */> offsetTable =
  12. new ConcurrentHashMap<Integer, Long>(32);
  13. public void start() {
  14. if (started.compareAndSet(false, true)) {
  15. this.timer = new Timer("ScheduleMessageTimerThread", true);
  16. // 为每个延时级别创建一个定时器,1s后执行
  17. for (Map.Entry<Integer, Long> entry : this.delayLevelTable.entrySet()) {
  18. Integer level = entry.getKey();
  19. Long timeDelay = entry.getValue();
  20. Long offset = this.offsetTable.get(level);
  21. if (null == offset) {
  22. offset = 0L;
  23. }
  24. if (timeDelay != null) {
  25. this.timer.schedule(new DeliverDelayedMessageTimerTask(level, offset), FIRST_DELAY_TIME);
  26. }
  27. }
  28. // 每隔10s持久化延时队列的消息消费进度
  29. this.timer.scheduleAtFixedRate(new TimerTask() {
  30. @Override
  31. public void run() {
  32. try {
  33. if (started.get()) ScheduleMessageService.this.persist();
  34. } catch (Throwable e) {
  35. log.error("scheduleAtFixedRate flush exception", e);
  36. }
  37. }
  38. }, 10000, this.defaultMessageStore.getMessageStoreConfig().getFlushDelayOffsetInterval());
  39. }
  40. }
  41. }
  42. public boolean load() {
  43. // 加载消费进度到offsetTable中
  44. boolean result = super.load();
  45. // 构造消息延时表
  46. result = result && this.parseDelayLevel();
  47. return result;
  48. }

ScheduleMessageService会为每个延时级别创建一个调度任务,可以看到实现类是DeliverDelayedMessageTimerTask

  1. /** * 定时调度任务实现类 */
  2. class DeliverDelayedMessageTimerTask extends TimerTask {
  3. private final int delayLevel;
  4. private final long offset;
  5. public DeliverDelayedMessageTimerTask(int delayLevel, long offset) {
  6. this.delayLevel = delayLevel;
  7. this.offset = offset;
  8. }
  9. @Override
  10. public void run() {
  11. try {
  12. if (isStarted()) {
  13. this.executeOnTimeup();
  14. }
  15. } catch (Exception e) {
  16. // XXX: warn and notify me
  17. log.error("ScheduleMessageService, executeOnTimeup exception", e);
  18. ScheduleMessageService.this.timer.schedule(new DeliverDelayedMessageTimerTask(
  19. this.delayLevel, this.offset), DELAY_FOR_A_PERIOD);
  20. }
  21. }
  22. public void executeOnTimeup() {
  23. // 查找消费队列
  24. ConsumeQueue cq =
  25. ScheduleMessageService.this.defaultMessageStore.findConsumeQueue(SCHEDULE_TOPIC,
  26. delayLevel2QueueId(delayLevel));
  27. long failScheduleOffset = offset;
  28. if (cq != null) {
  29. // 根据offset从消息消费队列中获取当前队列中所有有效的消息
  30. SelectMappedBufferResult bufferCQ = cq.getIndexBuffer(this.offset);
  31. if (bufferCQ != null) {
  32. try {
  33. long nextOffset = offset;
  34. int i = 0;
  35. ConsumeQueueExt.CqExtUnit cqExtUnit = new ConsumeQueueExt.CqExtUnit();
  36. // consumerQueue中每个消息是20字节,从起始消费进度开始解析出每个消息
  37. for (; i < bufferCQ.getSize(); i += ConsumeQueue.CQ_STORE_UNIT_SIZE) {
  38. long offsetPy = bufferCQ.getByteBuffer().getLong();
  39. int sizePy = bufferCQ.getByteBuffer().getInt();
  40. long tagsCode = bufferCQ.getByteBuffer().getLong();
  41. if (cq.isExtAddr(tagsCode)) {
  42. if (cq.getExt(tagsCode, cqExtUnit)) {
  43. tagsCode = cqExtUnit.getTagsCode();
  44. } else {
  45. //can't find ext content.So re compute tags code.
  46. log.error("[BUG] can't find consume queue extend file content!addr={}, offsetPy={}, sizePy={}",
  47. tagsCode, offsetPy, sizePy);
  48. long msgStoreTime = defaultMessageStore.getCommitLog().pickupStoreTimestamp(offsetPy, sizePy);
  49. tagsCode = computeDeliverTimestamp(delayLevel, msgStoreTime);
  50. }
  51. }
  52. long now = System.currentTimeMillis();
  53. long deliverTimestamp = this.correctDeliverTimestamp(now, tagsCode);
  54. // 下一次拉取的进度
  55. nextOffset = offset + (i / ConsumeQueue.CQ_STORE_UNIT_SIZE);
  56. long countdown = deliverTimestamp - now;
  57. // 判断延时消息到时间没,到时间就从commitLog取出来
  58. if (countdown <= 0) {
  59. // 根据偏移量和消息大小从commitLog文件中加载完整的消息
  60. MessageExt msgExt =
  61. ScheduleMessageService.this.defaultMessageStore.lookMessageByOffset(
  62. offsetPy, sizePy);
  63. if (msgExt != null) {
  64. try {
  65. // 创建一个新的消息,清除延时级别属性并恢复原来的主题和队列
  66. // 如果是普通消息,则是生产者发送时的topic和queueId
  67. // 如果时重试消息,则是重试的topic和queueId,在消费之前会再恢复成消息原本所属的topic
  68. MessageExtBrokerInner msgInner = this.messageTimeup(msgExt);
  69. // 将新的消息存入commitLog并转发给原本主题队列中供消费者消费
  70. PutMessageResult putMessageResult =
  71. ScheduleMessageService.this.writeMessageStore
  72. .putMessage(msgInner);
  73. if (putMessageResult != null
  74. && putMessageResult.getPutMessageStatus() == PutMessageStatus.PUT_OK) {
  75. continue;
  76. } else {
  77. // XXX: warn and notify me
  78. log.error(
  79. "ScheduleMessageService, a message time up, but reput it failed, topic: {} msgId {}",
  80. msgExt.getTopic(), msgExt.getMsgId());
  81. ScheduleMessageService.this.timer.schedule(
  82. new DeliverDelayedMessageTimerTask(this.delayLevel,
  83. nextOffset), DELAY_FOR_A_PERIOD);
  84. ScheduleMessageService.this.updateOffset(this.delayLevel,
  85. nextOffset);
  86. return;
  87. }
  88. } catch (Exception e) {
  89. /* * XXX: warn and notify me */
  90. log.error(
  91. "ScheduleMessageService, messageTimeup execute error, drop it. msgExt="
  92. + msgExt + ", nextOffset=" + nextOffset + ",offsetPy="
  93. + offsetPy + ",sizePy=" + sizePy, e);
  94. }
  95. }
  96. } else {
  97. // 差countdown到时间,就重新创建一个countdown时间后调度的定时器
  98. ScheduleMessageService.this.timer.schedule(
  99. new DeliverDelayedMessageTimerTask(this.delayLevel, nextOffset),
  100. countdown);
  101. // 更新前面时间到的消费进度
  102. ScheduleMessageService.this.updateOffset(this.delayLevel, nextOffset);
  103. // 前面的都没到时间,后面的肯定也没到时间,所以就不用再循环判断了,直接返回了
  104. return;
  105. }
  106. } // end of for
  107. nextOffset = offset + (i / ConsumeQueue.CQ_STORE_UNIT_SIZE);
  108. ScheduleMessageService.this.timer.schedule(new DeliverDelayedMessageTimerTask(
  109. this.delayLevel, nextOffset), DELAY_FOR_A_WHILE);
  110. // 更新该延时级别的消费进度
  111. ScheduleMessageService.this.updateOffset(this.delayLevel, nextOffset);
  112. return;
  113. } finally {
  114. bufferCQ.release();
  115. }
  116. } // end of if (bufferCQ != null)
  117. else {
  118. // 获取队列中最小的偏移量,如果该偏移量比之前的大,说明之前的偏移量是无效的,
  119. // 则下次从该偏移量开始获取
  120. long cqMinOffset = cq.getMinOffsetInQueue();
  121. if (offset < cqMinOffset) {
  122. failScheduleOffset = cqMinOffset;
  123. log.error("schedule CQ offset invalid. offset=" + offset + ", cqMinOffset="
  124. + cqMinOffset + ", queueId=" + cq.getQueueId());
  125. }
  126. }
  127. } // end of if (cq != null)
  128. // 没找到消费队列,就表示还没有重试消息,创建新的调度器,延迟100ms后重新调度
  129. ScheduleMessageService.this.timer.schedule(new DeliverDelayedMessageTimerTask(this.delayLevel,
  130. failScheduleOffset), DELAY_FOR_A_WHILE);
  131. }
  132. }

Step1:根据延时级别找到对应的消费队列。如果没找到,则忽略本次任务,重新创建一个调度任务。
Step2:根据offset从消息消费队列中获取当前队列中所有有效的消息bufferCQ,如果没找到,则要判断下offset是否比队列中的最小偏移量还小,如果小,则要替换,重新创建一个调度任务,下次获取就从最小的偏移量开始。
Step3:consumerQueue中每个消息是20字节,从第二步bufferCQ中开始循环解析出每个消息的物理偏移量,消息长度和tag hash,为从CommitLog中加载消息做准备。
Step4:判断延时消息到时间没,到时间就从commitLog取出来,根据物理偏移量和消息大小从commitLog文件中加载完整的消息。如果没到时间,则差多久到时间,就重新创建一个多久时间后执行调度任务,更新前面时间到的消费进度,然后返回。该调度任务到时间后也会按上面的步骤执行。
Step5:根据取出的消息重新构建新的消息对象,清除消息的延迟级别,并恢复消息原先的消息主题和消息消费队列。
Step6:将新的消息存入commitLog并转发给原本主题队列中供消费者消费。
Step7:更新延迟队列拉取进度。

总结:延时消息会有一个单独的topic:SCHEDULE_TOPIC_XXXX,所有的延时消息都发往该主题,该主题下的队列数量等于配置的延时级别数量,队列id=延时级别-1。每个延时级别都有一个定时任务,消息发送时,在broker端会将消息的原主题和队列id存入消息的属性中,然后改变消息的主题和队列,将消息存入到延时队列的消费队列中。
各个级别的定时任务根据延时拉取消息消费进度从延时队列中拉取消息,然后从commitLog文件中加载完整的消息,清除延时级别属性并恢复原来的主题和队列,再次创建一个新的消息存入到 commitLog中并转发到消息消费队列供消费者消费。
在这里插入图片描述

参考资料
《儒猿技术窝——从 0 开始带你成为消息中间件实战高手》

发表评论

表情:
评论列表 (有 0 条评论,157人围观)

还没有评论,来说两句吧...

相关阅读

    相关 RocketMQ进阶-消息

        前言 在开发中经常会遇到延时任务的需求,例如在12306购买车票,若生成订单30分钟未支付则自动取消;还有在线商城完成订单后48小时不评价 ,自动5星好评。像