• 再谈Rocket MQ消费进度问题


    若干种导致重复消费的可能性。彼时笔者认为即使网上普遍流传了众多原因但是如果洞悉了本质无非就是三点:

    • 网络自身是不可靠的,因此存在Client上报进度失败的情况

    • 进度的确认不可能是实时

      • 消费进度上报至Broker并非完全实时(5000ms/次)
      • Broker接受到消费进度并不会立即持久化
    • 消费进度持久化文件可能会丢失会篡改或者因为磁盘硬件原因被破坏

      但随着对Rocket MQ研究的深入,发现有些情况并不能笼统的归结于上述三种原因,这也是本篇文章的来源。

    负载均衡

    不管出于何种原因进行的负载均衡,如果之前分配到本Consumer的Queue本次分配到了别处,那么本Consumer必须将Queue对应的ProcessQueue置于废弃状态。下图是笔者针对定时Rebalancere任务绘制的执行路径。

    结合源码发现如果某个队列最后一次拉取时间已经超过120s且是Push模式的话也会认为该Queue已经不属于本Consumer。

    1. private boolean updateProcessQueueTableInRebalance(String topic, Set mqSet, boolean isOrder) {
    2. boolean changed = false;
    3. /* 处理本次负载均衡之后,应该被移除的队列 */
    4. Iterator<Entry<MessageQueue, ProcessQueue>> it = this.processQueueTable.entrySet().iterator();
    5. while (it.hasNext()) {
    6. Entry<MessageQueue, ProcessQueue> next = it.next();
    7. MessageQueue mq = next.getKey();
    8. ProcessQueue pq = next.getValue();
    9. /**
    10. * mq,pq 是目前该 Consumer 正在消费的
    11. * 如果负载均衡分配到的 Queue 集合中没有此 mq,则: ①、②、③
    12. */
    13. if (mq.getTopic().equals(topic)) {
    14. if (!mqSet.contains(mq)) {
    15. /* ①: 将该 pq 设置为废弃状态 */
    16. pq.setDropped(true);
    17. /* ②: 持久化待移除 MessageQueue 消费进度 */
    18. if (this.removeUnnecessaryMessageQueue(mq, pq)) {
    19. /* ③: 移除 processQueueTable 中的 mq、pq 信息 */
    20. it.remove();
    21. changed = true;
    22. log.info("doRebalance, {}, remove unnecessary mq, {}", consumerGroup, mq);
    23. }
    24. }
    25. /* (System.currentTimeMillis() - this.lastPullTimestamp) > PULL_MAX_IDLE_TIME */
    26. else if (pq.isPullExpired()) {
    27. switch (this.consumeType()) {
    28. case CONSUME_PASSIVELY:
    29. pq.setDropped(true);
    30. if (this.removeUnnecessaryMessageQueue(mq, pq)) {
    31. it.remove();
    32. changed = true;
    33. log.error("[BUG]doRebalance, {}, remove unnecessary mq, {}, because pull is pause, so try to fixed it", consumerGroup, mq);
    34. }
    35. break;
    36. case CONSUME_ACTIVELY:
    37. default:
    38. break;
    39. }
    40. }
    41. }
    42. }
    43. ......
    44. return changed;
    45. }

    一旦该队列在消息已经处于消费阶段,然后尚未提交进度之前被置于了废弃状态,那么该消息即使消费成功,也不能上报新的消费进度,这种情况的消息会因为进度不能上报而导致新的Consumer重复拉取到该消息。

    1. public void processConsumeResult(
    2. ConsumeConcurrentlyStatus status, ConsumeConcurrentlyContext context, ConsumeRequest consumeRequest
    3. ) {
    4. ......
    5. /* 获取当前 ProcessQueue#msgTreeMap 中最小的消息偏移量,并上报此偏移量作为消费进度 */
    6. long offset = consumeRequest.getProcessQueue().removeMessage(consumeRequest.getMsgs());
    7. if (offset >= 0 && !consumeRequest.getProcessQueue().isDropped()) {
    8. defaultMQPushConsumerImpl.getOffsetStore().updateOffset(consumeRequest.getMessageQueue(), offset, true);
    9. }
    10. }

    清理超时消息

    消息消费伊始会启动一个本地消息过期清理定时任务。 消息在Consumer端如果保留的时间超过固定时长,会触发重新投递逻辑。初始延迟时间、执行间隔相同,默认15min。

    1. /**
    2. * 定时执行cleanExpireMsg任务
    3. */
    4. public void start() {
    5. this.cleanExpireMsgExecutors.scheduleAtFixedRate(
    6. this::cleanExpireMsg,
    7. this.defaultMQPushConsumer.getConsumeTimeout(),
    8. this.defaultMQPushConsumer.getConsumeTimeout(),
    9. TimeUnit.MINUTES
    10. );
    11. }

    超时消息的清理逻辑封装在ProcessQueue中。在更新消费进度的处理中,只有消息被成功消费之后,才能从ProcessQueue中移除,清理逻辑中也是必须先重发消息成功之后才能在本地中移除该消息。这里会产生两种问题:

    • 如果清理线程命中的超时消息恰恰在这之后消费完毕,此时Rocket MQ依然感知不到该消息已经被消费,依然会重新投递。
    • 如果清理线程命中的超时消息重新投递之后且执行移除逻辑之前,消息恰好被消费线程消费,此时重投逻辑也已触发,覆水难收。
    1. public void cleanExpiredMsg(DefaultMQPushConsumer pushConsumer) {
    2. if (pushConsumer.getDefaultMQPushConsumerImpl().isConsumeOrderly()) {
    3. return;
    4. }
    5. int loop = Math.min(msgTreeMap.size(), 16);
    6. for (int i = 0; i < loop; i++) {
    7. MessageExt msg = null;
    8. try {
    9. this.lockTreeMap.readLock().lockInterruptibly();
    10. try {
    11. if (!msgTreeMap.isEmpty() &&
    12. System.currentTimeMillis() - Long.parseLong(
    13. MessageAccessor.getConsumeStartTimeStamp(
    14. msgTreeMap.firstEntry().getValue()
    15. )
    16. ) > pushConsumer.getConsumeTimeout() * 60 * 1000
    17. ) {
    18. msg = msgTreeMap.firstEntry().getValue();
    19. } else {
    20. break;
    21. }
    22. } finally {
    23. this.lockTreeMap.readLock().unlock();
    24. }
    25. } catch (InterruptedException e) {
    26. log.error("getExpiredMsg exception", e);
    27. }
    28. try {
    29. pushConsumer.sendMessageBack(msg, 3);
    30. /* 重发之后才移除,可能在这段时间这个消息已经消费了,有一个重复消费的场景 */
    31. log.info("send expire msg back. topic={}, msgId={}, storeHost={}, queueId={}, queueOffset={}", msg.getTopic(), msg.getMsgId(), msg.getStoreHost(), msg.getQueueId(), msg.getQueueOffset());
    32. try {
    33. this.lockTreeMap.writeLock().lockInterruptibly();
    34. try {
    35. if (!msgTreeMap.isEmpty() && msg.getQueueOffset() == msgTreeMap.firstKey()) {
    36. try {
    37. /**
    38. * 确定要被移除的消息是不是当前第一个消息(比对偏移量),符合条件说明msg还没有被消费掉可以移除
    39. * 从这里也能看出作者是知道第二种情形的
    40. */
    41. removeMessage(Collections.singletonList(msg));
    42. } catch (Exception e) {
    43. log.error("send expired msg exception", e);
    44. }
    45. }
    46. } finally {
    47. this.lockTreeMap.writeLock().unlock();
    48. }
    49. } catch (InterruptedException e) {
    50. log.error("getExpiredMsg exception", e);
    51. }
    52. } catch (Exception e) {
    53. log.error("send expired msg exception", e);
    54. }
    55. }
    56. }

    异常宕机

    异常退出,Rocket MQ重启之后会根据checkpoint文件中的时间点,确定可信的CommitLog文件,并从该文件开始构建ConsumeQueue、IndexFile文件,之一过程中完全有可能有的消息构建索引的动作执行了两次,自然会被消费两次,当然在业务看来这也会造成重复消费。

    1. public void recoverAbnormally(long maxPhyOffsetOfConsumeQueue) {
    2. /* recover by the minimum time stamp */
    3. boolean checkCRCOnRecover = this.defaultMessageStore.getMessageStoreConfig().isCheckCRCOnRecover();
    4. List mappedFiles = this.mappedFileQueue.getMappedFiles();
    5. if (!mappedFiles.isEmpty()) {
    6. /* Looking beginning to recover from which file */
    7. int index = mappedFiles.size() - 1;
    8. MappedFile mappedFile = null;
    9. for (; index >= 0; index--) {
    10. mappedFile = mappedFiles.get(index);
    11. /* 根据checkpoint文件确定起始可信文件 */
    12. if (this.isMappedFileMatchedRecover(mappedFile)) {
    13. log.info("recover from this mapped file " + mappedFile.getFileName());
    14. break;
    15. }
    16. }
    17. if (index < 0) {
    18. index = 0;
    19. mappedFile = mappedFiles.get(index);
    20. }
    21. ByteBuffer byteBuffer = mappedFile.sliceByteBuffer();
    22. long processOffset = mappedFile.getFileFromOffset();
    23. long mappedFileOffset = 0;
    24. while (true) {
    25. DispatchRequest dispatchRequest = this.checkMessageAndReturnSize(byteBuffer, checkCRCOnRecover);
    26. int size = dispatchRequest.getMsgSize();
    27. if (dispatchRequest.isSuccess()) {
    28. if (size > 0) {
    29. mappedFileOffset += size;
    30. if (this.defaultMessageStore.getMessageStoreConfig().isDuplicationEnable()) {
    31. /* 触发消息索引文件构建逻辑 */
    32. if (dispatchRequest.getCommitLogOffset() < this.defaultMessageStore.getConfirmOffset()) {
    33. this.defaultMessageStore.doDispatch(dispatchRequest);
    34. }
    35. } else {
    36. this.defaultMessageStore.doDispatch(dispatchRequest);
    37. }
    38. }
    39. // Come the end of the file, switch to the next file
    40. // Since the return 0 representatives met last hole, this can not be included in truncate offset
    41. else if (size == 0) {
    42. index++;
    43. if (index >= mappedFiles.size()) {
    44. /* The current branch under normal circumstances should not happen */
    45. log.info("recover physics file over, last mapped file " + mappedFile.getFileName());
    46. break;
    47. } else {
    48. mappedFile = mappedFiles.get(index);
    49. byteBuffer = mappedFile.sliceByteBuffer();
    50. processOffset = mappedFile.getFileFromOffset();
    51. mappedFileOffset = 0;
    52. log.info("recover next physics file, " + mappedFile.getFileName());
    53. }
    54. }
    55. } else {
    56. log.info("recover physics file end, " + mappedFile.getFileName() + " pos=" + byteBuffer.position());
    57. break;
    58. }
    59. }
    60. ......
    61. }
    62. ......
    63. }

    总结

    确如Rocket MQ官方定位"At least once"一样,作者完全没有纠结一些并发场景,和恢复之后的索引一致性问题。导致消息可能会被重复拉取、多次投递、以及多次构建索引......种种场景皆会导致业务上出现重复消费,因此消息的幂等保障必不可少

     

  • 相关阅读:
    微信小程序打开弹出层页面还可以滚动,导致弹出层和内容分离。不如筛选的时候。
    【并发编程五】c++进程通信——共享内存(shared memmory)
    springboot毕设项目宠物网络社区论坛系统sxg9h(java+VUE+Mybatis+Maven+Mysql)
    BGP&BGP4原理
    VUE-cesium(综合demo-01配置基础项)
    Mysql优化器-mysql详解(六)
    lable与input连用特殊动作效果
    《QT从基础到进阶·三十三》QT插件开发QtPlugin
    左神算法(一)下修改版
    深入解析kubernetes中的选举机制
  • 原文地址:https://blog.csdn.net/LBWNB_Java/article/details/126358989