• RocketMQ中Broker接收消息流程代码解析


    RocketMQ中,Broker通过SendMessageProcessor来接收和处理producer发送过来的消息。

    1. private RemotingCommand sendMessage(final ChannelHandlerContext ctx,
    2. final RemotingCommand request,
    3. final SendMessageContext sendMessageContext,
    4. final SendMessageRequestHeader requestHeader) throws RemotingCommandException {
    5. //1、构建Response的Header
    6. final RemotingCommand response = RemotingCommand.createResponseCommand(SendMessageResponseHeader.class);
    7. final SendMessageResponseHeader responseHeader = (SendMessageResponseHeader)response.readCustomHeader();
    8. response.setOpaque(request.getOpaque());
    9. response.addExtField(MessageConst.PROPERTY_MSG_REGION, this.brokerController.getBrokerConfig().getRegionId());
    10. response.addExtField(MessageConst.PROPERTY_TRACE_SWITCH, String.valueOf(this.brokerController.getBrokerConfig().isTraceOn()));
    11. log.debug("receive SendMessage request command, {}", request);
    12. //2、判断当前时间broker是否提供服务,不提供则返回code为SYSTEM_ERROR的response
    13. final long startTimstamp = this.brokerController.getBrokerConfig().getStartAcceptSendRequestTimeStamp();
    14. if (this.brokerController.getMessageStore().now() < startTimstamp) {//broker还没开始提供接收消息服务
    15. response.setCode(ResponseCode.SYSTEM_ERROR);
    16. response.setRemark(String.format("broker unable to service, until %s", UtilAll.timeMillisToHumanString2(startTimstamp)));
    17. return response;
    18. }
    19. response.setCode(-1);
    20. //3、检查topic和queue,如果不存在且broker设置中允许自动创建,则自动创建
    21. super.msgCheck(ctx, requestHeader, response);
    22. if (response.getCode() != -1) {
    23. return response;
    24. }
    25. final byte[] body = request.getBody();
    26. int queueIdInt = requestHeader.getQueueId();
    27. //4、获取topic的配置
    28. TopicConfig topicConfig = this.brokerController.getTopicConfigManager().selectTopicConfig(requestHeader.getTopic());
    29. //5、如果消息中的queueId小于0,则随机选取一个queue
    30. if (queueIdInt < 0) {
    31. queueIdInt = Math.abs(this.random.nextInt() % 99999999) % topicConfig.getWriteQueueNums();
    32. }
    33. //6、重新封装request中的message成MessageExtBrokerInner
    34. MessageExtBrokerInner msgInner = new MessageExtBrokerInner();
    35. msgInner.setTopic(requestHeader.getTopic());
    36. msgInner.setQueueId(queueIdInt);
    37. //7、对于RETRY消息,1)判断是否consumer还存在
    38. // 2)如果超过最大重发次数,尝试创建DLQ,并将topic设置成DeadQueue,消息将被存入死信队列
    39. if (!handleRetryAndDLQ(requestHeader, response, request, msgInner, topicConfig)) {
    40. return response;
    41. }
    42. msgInner.setBody(body);
    43. msgInner.setFlag(requestHeader.getFlag());
    44. MessageAccessor.setProperties(msgInner, MessageDecoder.string2messageProperties(requestHeader.getProperties()));
    45. msgInner.setPropertiesString(requestHeader.getProperties());
    46. msgInner.setBornTimestamp(requestHeader.getBornTimestamp());
    47. msgInner.setBornHost(ctx.channel().remoteAddress());
    48. msgInner.setStoreHost(this.getStoreHost());
    49. msgInner.setReconsumeTimes(requestHeader.getReconsumeTimes() == null ? 0 : requestHeader.getReconsumeTimes());
    50. PutMessageResult putMessageResult = null;
    51. Map oriProps = MessageDecoder.string2messageProperties(requestHeader.getProperties());
    52. String traFlag = oriProps.get(MessageConst.PROPERTY_TRANSACTION_PREPARED);
    53. if (traFlag != null && Boolean.parseBoolean(traFlag)) {
    54. //如果是事务消息
    55. if (this.brokerController.getBrokerConfig().isRejectTransactionMessage()) {
    56. response.setCode(ResponseCode.NO_PERMISSION);
    57. response.setRemark(
    58. "the broker[" + this.brokerController.getBrokerConfig().getBrokerIP1()
    59. + "] sending transaction message is forbidden");
    60. return response;
    61. }
    62. putMessageResult = this.brokerController.getTransactionalMessageService().prepareMessage(msgInner);
    63. } else {
    64. //8、调用MessageStore接口存储消息
    65. putMessageResult = this.brokerController.getMessageStore().putMessage(msgInner);
    66. }
    67. //9、根据putResult设置repsonse状态,更新broker统计信息,成功则回复producer,更新context上下文
    68. return handlePutMessageResult(putMessageResult, response, request, msgInner, responseHeader, sendMessageContext, ctx, queueIdInt);
    69. }

    在步骤3中,会对topic进行检查,如果topic不存在,且设置成自动创建topic,就会在Broker上自动创建topic。

    Broker最后调用MessageStore来存储数据。

    MessageStore保存消息

    DefaultMessageStore#putMessage
    1. public PutMessageResult putMessage(MessageExtBrokerInner msg) {
    2. if (this.shutdown) {
    3. log.warn("message store has shutdown, so putMessage is forbidden");
    4. return new PutMessageResult(PutMessageStatus.SERVICE_NOT_AVAILABLE, null);
    5. }
    6. // 从节点不允许写入
    7. if (BrokerRole.SLAVE == this.messageStoreConfig.getBrokerRole()) {
    8. long value = this.printTimes.getAndIncrement();
    9. if ((value % 50000) == 0) {
    10. log.warn("message store is slave mode, so putMessage is forbidden ");
    11. }
    12. return new PutMessageResult(PutMessageStatus.SERVICE_NOT_AVAILABLE, null);
    13. }
    14. // store是否允许写入
    15. if (!this.runningFlags.isWriteable()) {
    16. long value = this.printTimes.getAndIncrement();
    17. if ((value % 50000) == 0) {
    18. log.warn("message store is not writeable, so putMessage is forbidden " + this.runningFlags.getFlagBits());
    19. }
    20. return new PutMessageResult(PutMessageStatus.SERVICE_NOT_AVAILABLE, null);
    21. } else {
    22. this.printTimes.set(0);
    23. }
    24. // topic过长
    25. if (msg.getTopic().length() > Byte.MAX_VALUE) {
    26. log.warn("putMessage message topic length too long " + msg.getTopic().length());
    27. return new PutMessageResult(PutMessageStatus.MESSAGE_ILLEGAL, null);
    28. }
    29. // 消息附加属性过长
    30. if (msg.getPropertiesString() != null && msg.getPropertiesString().length() > Short.MAX_VALUE) {
    31. log.warn("putMessage message properties length too long " + msg.getPropertiesString().length());
    32. return new PutMessageResult(PutMessageStatus.PROPERTIES_SIZE_EXCEEDED, null);
    33. }
    34. if (this.isOSPageCacheBusy()) {
    35. return new PutMessageResult(PutMessageStatus.OS_PAGECACHE_BUSY, null);
    36. }
    37. long beginTime = this.getSystemClock().now();
    38. // 添加消息到commitLog
    39. PutMessageResult result = this.commitLog.putMessage(msg);
    40. long eclipseTime = this.getSystemClock().now() - beginTime;
    41. if (eclipseTime > 500) {
    42. log.warn("putMessage not in lock eclipse time(ms)={}, bodyLength={}", eclipseTime, msg.getBody().length);
    43. }
    44. this.storeStatsService.setPutMessageEntireTimeMax(eclipseTime);
    45. if (null == result || !result.isOk()) {
    46. this.storeStatsService.getPutMessageFailedTimes().incrementAndGet();
    47. }
    48. return result;
    49. }

    putMessage会做一下检查,然后调用CommitLog的putMessage方法来写入消息。

    CommitLog保存消息

    1. public PutMessageResult putMessage(final MessageExtBrokerInner msg) {
    2. // 1、Set the storage time
    3. msg.setStoreTimestamp(System.currentTimeMillis());
    4. // 2、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. // Delay Delivery
    17. if (msg.getDelayTimeLevel() > 0) {
    18. //3、延时投放消息,变更topic
    19. if (msg.getDelayTimeLevel() > this.defaultMessageStore.getScheduleMessageService().getMaxDelayLevel()) {
    20. msg.setDelayTimeLevel(this.defaultMessageStore.getScheduleMessageService().getMaxDelayLevel());
    21. }
    22. topic = ScheduleMessageService.SCHEDULE_TOPIC;
    23. queueId = ScheduleMessageService.delayLevel2QueueId(msg.getDelayTimeLevel());
    24. // Backup real topic, queueId
    25. MessageAccessor.putProperty(msg, MessageConst.PROPERTY_REAL_TOPIC, msg.getTopic());
    26. MessageAccessor.putProperty(msg, MessageConst.PROPERTY_REAL_QUEUE_ID, String.valueOf(msg.getQueueId()));
    27. msg.setPropertiesString(MessageDecoder.messageProperties2String(msg.getProperties()));
    28. msg.setTopic(topic);
    29. msg.setQueueId(queueId);
    30. }
    31. }
    32. long eclipseTimeInLock = 0;
    33. MappedFile unlockMappedFile = null;
    34. //4、获取当前正在写入文件
    35. MappedFile mappedFile = this.mappedFileQueue.getLastMappedFile();
    36. //5、获取写message的锁
    37. putMessageLock.lock(); //spin or ReentrantLock ,depending on store config
    38. try {
    39. long beginLockTimestamp = this.defaultMessageStore.getSystemClock().now();
    40. this.beginTimeInLock = beginLockTimestamp;//记录lock time
    41. // Here settings are stored timestamp, in order to ensure an orderly
    42. // global
    43. msg.setStoreTimestamp(beginLockTimestamp);
    44. //6、新建一个mapp file如果文件不存在或者文件已经写满
    45. if (null == mappedFile || mappedFile.isFull()) {
    46. mappedFile = this.mappedFileQueue.getLastMappedFile(0); // Mark: NewFile may be cause noise
    47. }
    48. if (null == mappedFile) {
    49. //文件创建失败,则返回错误
    50. log.error("create mapped file1 error, topic: " + msg.getTopic() + " clientAddr: " + msg.getBornHostString());
    51. beginTimeInLock = 0;
    52. return new PutMessageResult(PutMessageStatus.CREATE_MAPEDFILE_FAILED, null);
    53. }
    54. //7、消息写文件
    55. result = mappedFile.appendMessage(msg, this.appendMessageCallback);
    56. switch (result.getStatus()) {
    57. case PUT_OK:
    58. break;
    59. case END_OF_FILE:
    60. //8、如果文件已满,则新建一个文件继续
    61. unlockMappedFile = mappedFile;
    62. // Create a new file, re-write the message
    63. mappedFile = this.mappedFileQueue.getLastMappedFile(0);
    64. if (null == mappedFile) {
    65. log.error("create mapped file2 error, topic: " + msg.getTopic() + " clientAddr: " + msg.getBornHostString());
    66. beginTimeInLock = 0;
    67. return new PutMessageResult(PutMessageStatus.CREATE_MAPEDFILE_FAILED, result);
    68. }
    69. result = mappedFile.appendMessage(msg, this.appendMessageCallback);
    70. break;
    71. case MESSAGE_SIZE_EXCEEDED:
    72. case PROPERTIES_SIZE_EXCEEDED:
    73. beginTimeInLock = 0;
    74. return new PutMessageResult(PutMessageStatus.MESSAGE_ILLEGAL, result);
    75. case UNKNOWN_ERROR:
    76. beginTimeInLock = 0;
    77. return new PutMessageResult(PutMessageStatus.UNKNOWN_ERROR, result);
    78. default:
    79. beginTimeInLock = 0;
    80. return new PutMessageResult(PutMessageStatus.UNKNOWN_ERROR, result);
    81. }
    82. eclipseTimeInLock = this.defaultMessageStore.getSystemClock().now() - beginLockTimestamp;
    83. beginTimeInLock = 0;
    84. } finally {
    85. //9、释放第5)步中获取到的锁
    86. putMessageLock.unlock();
    87. }
    88. if (eclipseTimeInLock > 500) {//写消息时间过长
    89. log.warn("[NOTIFYME]putMessage in lock cost time(ms)={}, bodyLength={} AppendMessageResult={}", eclipseTimeInLock, msg.getBody().length, result);
    90. }
    91. //unlock已经写满的文件,释放内存锁
    92. if (null != unlockMappedFile && this.defaultMessageStore.getMessageStoreConfig().isWarmMapedFileEnable()) {
    93. this.defaultMessageStore.unlockMappedFile(unlockMappedFile);
    94. }
    95. PutMessageResult putMessageResult = new PutMessageResult(PutMessageStatus.PUT_OK, result);
    96. // Statistics
    97. storeStatsService.getSinglePutMessageTopicTimesTotal(msg.getTopic()).incrementAndGet();
    98. storeStatsService.getSinglePutMessageTopicSizeTotal(topic).addAndGet(result.getWroteBytes());
    99. //10、flush数据到磁盘,分同步和异步
    100. handleDiskFlush(result, putMessageResult, msg);
    101. //11、如果broker设置成SYNC_MASTER,则等SLAVE接收到数据后才返回(接收到数据是指offset延后没有超过制定的字节数)
    102. handleHA(result, putMessageResult, msg);
    103. return putMessageResult;
    104. }
    • 第3步,判断是否是Consumer发来的Retry消息,如果是则修改topic为 SCHEDULE_TOPIC_XXXX,根据延时时长计算queueId。将原始的topic和queueId放到消息的properties字段中。这样这个消息只会被重发的Schedule任务读到。
    • 第4步,前面讲MessageStore的时候讲过,CommitLog是由连续的MappedFile的列表组成的。在同一时间,只有最后一个MappedFile有写入,因为之前的文件都已经写满了,所以这里是取最后一个。
    • 第6步,如果commitLog是第一次启动,或者文件size已经达到maxSize,则新建一个文件
    • 第7步,将消息内容写入MappedFile,这里会传一个callback的参数,真正的写入是在callback中实现的,后面我们再看这个实现
    • 第8步,在上一步中的appendMessage()接口中,如果文件剩余的空间已经不足以写下这条消息,则会用一个EOF消息补齐文件,然后返回一个EOF错误。在收到这个错误时,会新建一个文件,然后重写一次。
    • 第10步,用户可以使用MessageStoreFlushDiskType参数来控制数据flush到磁盘的方式,如果参数值SYNC_FLUSH,则每次写完消息都会做一次flush,完成才会返回结果。如果是ASYNC_FLUSH,只会唤醒flushCommitLogService,由它异步的去检查是否要做flush。
    • 第9步,Broker的主从数据同步也可以有两种方式,如果是SYNC_MASTER,则Master保存消息后,需要将消息同步给slave后才会返回结果。如果ASYNC_MASTER,这里不会做任何操作,由HAService的后台线程做数据同步。

    MappedFile消息写入

    1. public AppendMessageResult appendMessagesInner(final MessageExt messageExt, final AppendMessageCallback cb) {
    2. assert messageExt != null;
    3. assert cb != null;
    4. //1、获取当前的write position
    5. int currentPos = this.wrotePosition.get();
    6. if (currentPos < this.fileSize) {
    7. //2、生成buffer切片
    8. ByteBuffer byteBuffer = writeBuffer != null ? writeBuffer.slice() : this.mappedByteBuffer.slice();
    9. byteBuffer.position(currentPos);
    10. AppendMessageResult result = null;
    11. if (messageExt instanceof MessageExtBrokerInner) {
    12. //3、写单条消息到byteBuffer
    13. result = cb.doAppend(this.getFileFromOffset(), byteBuffer, this.fileSize - currentPos, (MessageExtBrokerInner) messageExt);
    14. } else if (messageExt instanceof MessageExtBatch) {
    15. //3、批量消息到byteBuffer
    16. result = cb.doAppend(this.getFileFromOffset(), byteBuffer, this.fileSize - currentPos, (MessageExtBatch) messageExt);
    17. } else {
    18. return new AppendMessageResult(AppendMessageStatus.UNKNOWN_ERROR);
    19. }
    20. //4、更新write position,到最新值
    21. this.wrotePosition.addAndGet(result.getWroteBytes());
    22. this.storeTimestamp = result.getStoreTimestamp();
    23. return result;
    24. }
    25. log.error("MappedFile.appendMessage return null, wrotePosition: {} fileSize: {}", currentPos, this.fileSize);
    26. return new AppendMessageResult(AppendMessageStatus.UNKNOWN_ERROR);
    27. }

    消息写入首先是获取ByteBuffer,从第2步中可以发现有个判断,这里是因为MappedFile写数据到文件有两种实现方式:

    • FileChannel获取直接内存映射,收到消息后,将数据写入到这块内存中,内存和物理文件的数据交互由操作系统负责
    • CommitLog启动的时候初始化一块内存池(通过ByteBuffer申请的堆外内存),消息数据首先写入内存池中,然后后台有个线程定时将内存池中的数据commit到FileChannel中。这种方式只有MessageStore是ASYNC模式时才能开启。代码中if判断writeBuffer不为空的情况就是使用的这种写入方式。

    第3步,最终回调的Callback类将数据写入buffer中,消息的序列化也是在callback里面完成的。

  • 相关阅读:
    【智慧排水】智慧排水监测系统助力城市抗洪排涝建设
    (个人杂记)第九章 串口中断3
    学习python第7天
    MySQL如何一劳永逸的永久支持输入中文
    如何解决golang开发中遇到的报错:checksum mismatch downloaded
    实现注册手机号用户
    springcloudalibaba架构(1):如何实现服务调用Ribbon和Feign
    用最少的代码模拟gRPC四种消息交换模式
    ChatGPT:Spring Boot和Maven——Java应用开发的关键工具和区别
    精品Python商铺摊位租赁管理系统
  • 原文地址:https://blog.csdn.net/bao2901203013/article/details/126202374