1. 高级功能

1.1 消息存储

分布式队列因为有高可靠性的要求,所以数据要进行持久化存储。
RocketMQ-03 - 图10

  1. 消息生成者发送消息
  2. MQ收到消息,将消息进行持久化,在存储中新增一条记录
  3. 返回ACK给生产者
  4. MQ push 消息给对应的消费者,然后等待消费者返回ACK
  5. 如果消息消费者在指定时间内成功返回ack,那么MQ认为消息消费成功,在存储中删除消息,即执行第6步;如果MQ在指定时间内没有收到ACK,则认为消息消费失败,会尝试重新push消息,重复执行4、5、6步骤
  6. MQ删除消息

    1.1.1 存储介质

  • 关系型数据库DB

Apache下开源的另外一款MQ—ActiveMQ(默认采用的KahaDB做消息存储)可选用JDBC的方式来做消息持久化,通过简单的xml配置信息即可实现JDBC消息存储。由于,普通关系型数据库(如Mysql)在单表数据量达到千万级别的情况下,其IO读写性能往往会出现瓶颈。在可靠性方面,该种方案非常依赖DB,如果一旦DB出现故障,则MQ的消息就无法落盘存储会导致线上故障
RocketMQ-03 - 图11

  • 文件系统
    目前业界较为常用的几款产品(RocketMQ/Kafka/RabbitMQ)均采用的是消息刷盘至所部署虚拟机/物理机的文件系统来做持久化(刷盘一般可以分为异步刷盘和同步刷盘两种模式)。消息刷盘为消息存储提供了一种高效率、高可靠性和高性能的数据持久化方式。除非部署MQ机器本身或是本地磁盘挂了,否则一般是不会出现无法持久化的故障问题。
    RocketMQ-03 - 图12

    1.1.2 性能对比

    文件系统>关系型数据库DB

    1.1.3 消息的存储和发送

    1)消息存储

    磁盘如果使用得当,磁盘的速度完全可以匹配上网络 的数据传输速度。目前的高性能磁盘,顺序写速度可以达到600MB/s, 超过了一般网卡的传输速度。但是磁盘随机写的速度只有大概100KB/s,和顺序写的性能相差6000倍!因为有如此巨大的速度差别,好的消息队列系统会比普通的消息队列系统速度快多个数量级。RocketMQ的消息用顺序写,保证了消息存储的速度。
    ####2)消息发送
    Linux操作系统分为【用户态】和【内核态】,文件操作、网络操作需要涉及这两种形态的切换,免不了进行数据复制。
    一台服务器 把本机磁盘文件的内容发送到客户端,一般分为两个步骤:
    1)read;读取本地文件内容;
    2)write;将读取的内容通过网络发送出去。
    这两个看似简单的操作,实际进行了4 次数据复制,分别是:
  1. 从磁盘复制数据到内核态内存;
  2. 从内核态内存复 制到用户态内存;
  3. 然后从用户态 内存复制到网络驱动的内核态内存;
  4. 最后是从网络驱动的内核态内存复 制到网卡中进行传输。

RocketMQ-03 - 图13%E9%80%9A%E8%BF%87%E4%BD%BF%E7%94%A8mmap%E7%9A%84%E6%96%B9%E5%BC%8F,%E5%8F%AF%E4%BB%A5%E7%9C%81%E5%8E%BB%E5%90%91%E7%94%A8%E6%88%B7%E6%80%81%E7%9A%84%E5%86%85%E5%AD%98%E5%A4%8D%E5%88%B6,%E6%8F%90%E9%AB%98%E9%80%9F%E5%BA%A6。%E8%BF%99%E7%A7%8D%E6%9C%BA%E5%88%B6%E5%9C%A8Java%E4%B8%AD%E6%98%AF%E9%80%9A%E8%BF%87MappedByteBuffer%E5%AE%9E%E7%8E%B0%E7%9A%84
RocketMQ充分利用了上述特性,也就是所谓的“零拷贝”技术,提高消息存盘和网络发送的速度。

这里需要注意的是,采用MappedByteBuffer这种内存映射的方式有几个限制,其中之一是一次只能映射1.5~2G 的文件至用户态的虚拟内存,这也是为何RocketMQ默认设置单个CommitLog日志数据文件为1G的原因了

1.1.4 消息存储结构

RocketMQ消息的存储是由ConsumeQueue和CommitLog配合完成 的,消息真正的物理存储文件是CommitLog,ConsumeQueue是消息的逻辑队列,类似数据库的索引文件,存储的是指向物理存储的地址。每 个Topic下的每个Message Queue都有一个对应的ConsumeQueue文件。
RocketMQ-03 - 图14

  • CommitLog:存储消息的元数据
  • ConsumerQueue:存储消息在CommitLog的索引
  • IndexFile:为了消息查询提供了一种通过key或时间区间来查询消息的方法,这种通过IndexFile来查找消息的方法不影响发送与消费消息的主流程

    1.1.5 刷盘机制

    RocketMQ的消息是存储到磁盘上的,这样既能保证断电后恢复, 又可以让存储的消息量超出内存的限制。RocketMQ为了提高性能,会尽可能地保证磁盘的顺序写。消息在通过Producer写入RocketMQ的时 候,有两种写磁盘方式,分布式同步刷盘和异步刷盘。
    RocketMQ-03 - 图15

    1)同步刷盘

    在返回写成功状态时,消息已经被写入磁盘。具体流程是,消息写入内存的PAGECACHE后,立刻通知刷盘线程刷盘, 然后等待刷盘完成,刷盘线程执行完成后唤醒等待的线程,返回消息写 成功的状态。

    2)异步刷盘

    在返回写成功状态时,消息可能只是被写入了内存的PAGECACHE,写操作的返回快,吞吐量大;当内存里的消息量积累到一定程度时,统一触发写磁盘动作,快速写入。
    ####3)配置
    同步刷盘还是异步刷盘,都是通过Broker配置文件里的flushDiskType 参数设置的,这个参数被配置成SYNC_FLUSH、ASYNC_FLUSH中的 一个。

    1.2 高可用性机制

    RocketMQ-03 - 图16
    RocketMQ分布式集群是通过Master和Slave的配合达到高可用性的。
    Master和Slave的区别:在Broker的配置文件中,参数 brokerId的值为0表明这个Broker是Master,大于0表明这个Broker是 Slave,同时brokerRole参数也会说明这个Broker是Master还是Slave。
    Master角色的Broker支持读和写,Slave角色的Broker仅支持读,也就是 Producer只能和Master角色的Broker连接写入消息;Consumer可以连接 Master角色的Broker,也可以连接Slave角色的Broker来读取消息。

    1.2.1 消息消费高可用

    在Consumer的配置文件中,并不需要设置是从Master读还是从Slave 读,当Master不可用或者繁忙的时候,Consumer会被自动切换到从Slave 读。有了自动切换Consumer这种机制,当一个Master角色的机器出现故障后,Consumer仍然可以从Slave读取消息,不影响Consumer程序。这就达到了消费端的高可用性。

    1.2.2 消息发送高可用

    在创建Topic的时候,把Topic的多个Message Queue创建在多个Broker组上(相同Broker名称,不同 brokerId的机器组成一个Broker组),这样当一个Broker组的Master不可 用后,其他组的Master仍然可用,Producer仍然可以发送消息。 RocketMQ目前还不支持把Slave自动转成Master,如果机器资源不足, 需要把Slave转成Master,则要手动停止Slave角色的Broker,更改配置文 件,用新的配置文件启动Broker。
    RocketMQ-03 - 图17

    1.2.3 消息主从复制

    如果一个Broker组有Master和Slave,消息需要从Master复制到Slave 上,有同步和异步两种复制方式。
    ####1)同步复制
    同步复制方式是等Master和Slave均写 成功后才反馈给客户端写成功状态;
    在同步复制方式下,如果Master出故障, Slave上有全部的备份数据,容易恢复,但是同步复制会增大数据写入 延迟,降低系统吞吐量。
    ####2)异步复制
    异步复制方式是只要Master写成功 即可反馈给客户端写成功状态。
    在异步复制方式下,系统拥有较低的延迟和较高的吞吐量,但是如果Master出了故障,有些数据因为没有被写 入Slave,有可能会丢失;
    ####3)配置
    同步复制和异步复制是通过Broker配置文件里的brokerRole参数进行设置的,这个参数可以被设置成ASYNC_MASTER、 SYNC_MASTER、SLAVE三个值中的一个。
    ####4)总结
    RocketMQ-03 - 图18
    实际应用中要结合业务场景,合理设置刷盘方式和主从复制方式, 尤其是SYNC_FLUSH方式,由于频繁地触发磁盘写动作,会明显降低 性能。通常情况下,应该把Master和Save配置成ASYNC_FLUSH的刷盘 方式,主从之间配置成SYNC_MASTER的复制方式,这样即使有一台 机器出故障,仍然能保证数据不丢,是个不错的选择。

    1.3 负载均衡

    1.3.1 Producer负载均衡

    Producer端,每个实例在发消息的时候,默认会轮询所有的message queue发送,以达到让消息平均落在不同的queue上。而由于queue可以散落在不同的broker,所以消息就发送到不同的broker下,如下图:
    RocketMQ-03 - 图19
    图中箭头线条上的标号代表顺序,发布方会把第一条消息发送至 Queue 0,然后第二条消息发送至 Queue 1,以此类推。

    1.3.2 Consumer负载均衡

    1)集群模式

    在集群消费模式下,每条消息只需要投递到订阅这个topic的Consumer Group下的一个实例即可。RocketMQ采用主动拉取的方式拉取并消费消息,在拉取的时候需要明确指定拉取哪一条message queue。
    而每当实例的数量有变更,都会触发一次所有实例的负载均衡,这时候会按照queue的数量和实例的数量平均分配queue给每个实例。
    默认的分配算法是AllocateMessageQueueAveragely,如下图:
    RocketMQ-03 - 图20
    还有另外一种平均的算法是AllocateMessageQueueAveragelyByCircle,也是平均分摊每一条queue,只是以环状轮流分queue的形式,如下图:
    RocketMQ-03 - 图21
    需要注意的是,集群模式下,queue都是只允许分配只一个实例,这是由于如果多个实例同时消费一个queue的消息,由于拉取哪些消息是consumer主动控制的,那样会导致同一个消息在不同的实例下被消费多次,所以算法上都是一个queue只分给一个consumer实例,一个consumer实例可以允许同时分到不同的queue。
    通过增加consumer实例去分摊queue的消费,可以起到水平扩展的消费能力的作用。而有实例下线的时候,会重新触发负载均衡,这时候原来分配到的queue将分配到其他实例上继续消费。
    但是如果consumer实例的数量比message queue的总数量还多的话,多出来的consumer实例将无法分到queue,也就无法消费到消息,也就无法起到分摊负载的作用了。所以需要控制让queue的总数量大于等于consumer的数量。
    ####2)广播模式
    由于广播模式下要求一条消息需要投递到一个消费组下面所有的消费者实例,所以也就没有消息被分摊消费的说法。
    在实现上,其中一个不同就是在consumer分配queue的时候,所有consumer都分到所有的queue。
    RocketMQ-03 - 图22

    1.4 消息重试

    1.4.1 顺序消息的重试

    对于顺序消息,当消费者消费消息失败后,消息队列 RocketMQ 会自动不断进行消息重试(每次间隔时间为 1 秒),这时,应用会出现消息消费被阻塞的情况。因此,在使用顺序消息时,务必保证应用能够及时监控并处理消费失败的情况,避免阻塞现象的发生。

    1.4.2 无序消息的重试

    对于无序消息(普通、定时、延时、事务消息),当消费者消费消息失败时,您可以通过设置返回状态达到消息重试的结果。
    无序消息的重试只针对集群消费方式生效;广播方式不提供失败重试特性,即消费失败后,失败消息不再重试,继续消费新的消息。

    1)重试次数

    消息队列 RocketMQ 默认允许每条消息最多重试 16 次,每次重试的间隔时间如下:
第几次重试 与上次重试的间隔时间 第几次重试 与上次重试的间隔时间
1 10 秒 9 7 分钟
2 30 秒 10 8 分钟
3 1 分钟 11 9 分钟
4 2 分钟 12 10 分钟
5 3 分钟 13 20 分钟
6 4 分钟 14 30 分钟
7 5 分钟 15 1 小时
8 6 分钟 16 2 小时

如果消息重试 16 次后仍然失败,消息将不再投递。如果严格按照上述重试时间间隔计算,某条消息在一直消费失败的前提下,将会在接下来的 4 小时 46 分钟之内进行 16 次重试,超过这个时间范围消息将不再重试投递。
注意: 一条消息无论重试多少次,这些重试消息的 Message ID 不会改变。

2)配置方式

消费失败后,重试配置方式
集群消费方式下,消息消费失败后期望消息重试,需要在消息监听器接口的实现中明确进行配置(三种方式任选一种):

  • 返回 Action.ReconsumeLater (推荐)
  • 返回 Null
  • 抛出异常

    1. public class MessageListenerImpl implements MessageListener {
    2. @Override
    3. public Action consume(Message message, ConsumeContext context) {
    4. //处理消息
    5. doConsumeMessage(message);
    6. //方式1:返回 Action.ReconsumeLater,消息将重试
    7. return Action.ReconsumeLater;
    8. //方式2:返回 null,消息将重试
    9. return null;
    10. //方式3:直接抛出异常, 消息将重试
    11. throw new RuntimeException("Consumer Message exceotion");
    12. }
    13. }

    消费失败后,不重试配置方式
    集群消费方式下,消息失败后期望消息不重试,需要捕获消费逻辑中可能抛出的异常,最终返回 Action.CommitMessage,此后这条消息将不会再重试。

    1. public class MessageListenerImpl implements MessageListener {
    2. @Override
    3. public Action consume(Message message, ConsumeContext context) {
    4. try {
    5. doConsumeMessage(message);
    6. } catch (Throwable e) {
    7. //捕获消费逻辑中的所有异常,并返回 Action.CommitMessage;
    8. return Action.CommitMessage;
    9. }
    10. //消息处理正常,直接返回 Action.CommitMessage;
    11. return Action.CommitMessage;
    12. }
    13. }

    自定义消息最大重试次数
    消息队列 RocketMQ 允许 Consumer 启动的时候设置最大重试次数,重试时间间隔将按照如下策略:

  • 最大重试次数小于等于 16 次,则重试时间间隔同上表描述。

  • 最大重试次数大于 16 次,超过 16 次的重试时间间隔均为每次 2 小时。

    1. Properties properties = new Properties();
    2. //配置对应 Group ID 的最大消息重试次数为 20 次
    3. properties.put(PropertyKeyConst.MaxReconsumeTimes,"20");
    4. Consumer consumer =ONSFactory.createConsumer(properties);

    注意:

  • 消息最大重试次数的设置对相同 Group ID 下的所有 Consumer 实例有效。

  • 如果只对相同 Group ID 下两个 Consumer 实例中的其中一个设置了 MaxReconsumeTimes,那么该配置对两个 Consumer 实例均生效。
  • 配置采用覆盖的方式生效,即最后启动的 Consumer 实例会覆盖之前的启动实例的配置

获取消息重试次数
消费者收到消息后,可按照如下方式获取消息的重试次数:

  1. public class MessageListenerImpl implements MessageListener {
  2. @Override
  3. public Action consume(Message message, ConsumeContext context) {
  4. //获取消息的重试次数
  5. System.out.println(message.getReconsumeTimes());
  6. return Action.CommitMessage;
  7. }
  8. }

1.5 死信队列

当一条消息初次消费失败,消息队列 RocketMQ 会自动进行消息重试;达到最大重试次数后,若消费依然失败,则表明消费者在正常情况下无法正确地消费该消息,此时,消息队列 RocketMQ 不会立刻将消息丢弃,而是将其发送到该消费者对应的特殊队列中。
在消息队列 RocketMQ 中,这种正常情况下无法被消费的消息称为死信消息(Dead-Letter Message),存储死信消息的特殊队列称为死信队列(Dead-Letter Queue)。

1.5.1 死信特性

死信消息具有以下特性

  • 不会再被消费者正常消费。
  • 有效期与正常消息相同,均为 3 天,3 天后会被自动删除。因此,请在死信消息产生后的 3 天内及时处理。

死信队列具有以下特性:

  • 一个死信队列对应一个 Group ID, 而不是对应单个消费者实例。
  • 如果一个 Group ID 未产生死信消息,消息队列 RocketMQ 不会为其创建相应的死信队列。
  • 一个死信队列包含了对应 Group ID 产生的所有死信消息,不论该消息属于哪个 Topic。

    1.5.2 查看死信信息

  1. 在控制台查询出现死信队列的主题信息

RocketMQ-03 - 图23

  1. 在消息界面根据主题查询死信消息

RocketMQ-03 - 图24

  1. 选择重新发送消息

一条消息进入死信队列,意味着某些因素导致消费者无法正常消费该消息,因此,通常需要您对其进行特殊处理。排查可疑因素并解决问题后,可以在消息队列 RocketMQ 控制台重新发送该消息,让消费者重新消费一次。

1.6 消费幂等

消息队列 RocketMQ 消费者在接收到消息以后,有必要根据业务上的唯一 Key 对消息做幂等处理的必要性。

1.6.1 消费幂等的必要性

在互联网应用中,尤其在网络不稳定的情况下,消息队列 RocketMQ 的消息有可能会出现重复,这个重复简单可以概括为以下情况:

  • 发送时消息重复
    当一条消息已被成功发送到服务端并完成持久化,此时出现了网络闪断或者客户端宕机,导致服务端对客户端应答失败。 如果此时生产者意识到消息发送失败并尝试再次发送消息,消费者后续会收到两条内容相同并且 Message ID 也相同的消息。
  • 投递时消息重复
    消息消费的场景下,消息已投递到消费者并完成业务处理,当客户端给服务端反馈应答的时候网络闪断。 为了保证消息至少被消费一次,消息队列 RocketMQ 的服务端将在网络恢复后再次尝试投递之前已被处理过的消息,消费者后续会收到两条内容相同并且 Message ID 也相同的消息。
  • 负载均衡时消息重复(包括但不限于网络抖动、Broker 重启以及订阅方应用重启)
    当消息队列 RocketMQ 的 Broker 或客户端重启、扩容或缩容时,会触发 Rebalance,此时消费者可能会收到重复消息。

    1.6.2 处理方式

    因为 Message ID 有可能出现冲突(重复)的情况,所以真正安全的幂等处理,不建议以 Message ID 作为处理依据。 最好的方式是以业务唯一标识作为幂等处理的关键依据,而业务的唯一标识可以通过消息 Key 进行设置:

    1. Message message = new Message();
    2. message.setKey("ORDERID_100");
    3. SendResult sendResult = producer.send(message);

    订阅方收到消息时可以根据消息的 Key 进行幂等处理:

    1. consumer.subscribe("ons_test", "*", new MessageListener() {
    2. public Action consume(Message message, ConsumeContext context) {
    3. String key = message.getKey()
    4. // 根据业务唯一标识的 key 做幂等处理
    5. }
    6. });

    2. 源码分析

    2.1 环境搭建

    依赖工具

  • JDK :1.8+

  • Maven
  • IntelliJ IDEA

    2.1.1 源码拉取

    从官方仓库 https://github.com/apache/rocketmq clone或者download源码。
    RocketMQ-03 - 图25
    源码目录结构:

  • broker: broker 模块(broke 启动进程)

  • client :消息客户端,包含消息生产者、消息消费者相关类
  • common :公共包
  • dev :开发者信息(非源代码)
  • distribution :部署实例文件夹(非源代码)
  • example: RocketMQ 例代码
  • filter :消息过滤相关基础类
  • filtersrv:消息过滤服务器实现相关类(Filter启动进程)
  • logappender:日志实现相关类
  • namesrv:NameServer实现相关类(NameServer启动进程)
  • openmessageing:消息开放标准
  • remoting:远程通信模块,给予Netty
  • srcutil:服务工具类
  • store:消息存储实现相关类
  • style:checkstyle相关实现
  • test:测试相关类
  • tools:工具类,监控命令相关实现类

2.1.2 导入IDEA
RocketMQ-03 - 图26
执行安装

  1. clean install -Dmaven.test.skip=true

2.1.3 调试

创建conf配置文件夹,从distribution拷贝broker.conflogback_broker.xmllogback_namesrv.xml
RocketMQ-03 - 图27

1)启动NameServer

  • 展开namesrv模块,右键NamesrvStartup.java

RocketMQ-03 - 图28

  • 配置ROCKETMQ_HOME

RocketMQ-03 - 图29
RocketMQ-03 - 图30

  • 重新启动
    控制台打印结果

    1. The Name Server boot success. serializeType=JSON

    2)启动Broker

  • broker.conf配置文件内容

    1. brokerClusterName = DefaultCluster
    2. brokerName = broker-a
    3. brokerId = 0
    4. # namesrvAddr地址
    5. namesrvAddr=127.0.0.1:9876
    6. deleteWhen = 04
    7. fileReservedTime = 48
    8. brokerRole = ASYNC_MASTER
    9. flushDiskType = ASYNC_FLUSH
    10. autoCreateTopicEnable=true
    11. # 存储路径
    12. storePathRootDir=E:\\RocketMQ\\data\\rocketmq\\dataDir
    13. # commitLog路径
    14. storePathCommitLog=E:\\RocketMQ\\data\\rocketmq\\dataDir\\commitlog
    15. # 消息队列存储路径
    16. storePathConsumeQueue=E:\\RocketMQ\\data\\rocketmq\\dataDir\\consumequeue
    17. # 消息索引存储路径
    18. storePathIndex=E:\\RocketMQ\\data\\rocketmq\\dataDir\\index
    19. # checkpoint文件路径
    20. storeCheckpoint=E:\\RocketMQ\\data\\rocketmq\\dataDir\\checkpoint
    21. # abort文件存储路径
    22. abortFile=E:\\RocketMQ\\data\\rocketmq\\dataDir\\abort
  • 创建数据文件夹dataDir

  • 启动BrokerStartup,配置broker.confROCKETMQ_HOME

RocketMQ-03 - 图31
RocketMQ-03 - 图32
####3)发送消息

  • 进入example模块的org.apache.rocketmq.example.quickstart
  • 指定Namesrv地址

    1. DefaultMQProducer producer = new DefaultMQProducer("please_rename_unique_group_name");
    2. producer.setNamesrvAddr("127.0.0.1:9876");
  • 运行main方法,发送消息

    4)消费消息

  • 进入example模块的org.apache.rocketmq.example.quickstart

  • 指定Namesrv地址

    1. DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("please_rename_unique_group_name_4");
    2. consumer.setNamesrvAddr("127.0.0.1:9876");
  • 运行main方法,消费消息

    2.2 NameServer

    2.2.1 架构设计

    消息中间件的设计思路一般是基于主题订阅发布的机制,消息生产者(Producer)发送某一个主题到消息服务器,消息服务器负责将消息持久化存储,消息消费者(Consumer)订阅该兴趣的主题,消息服务器根据订阅信息(路由信息)将消息推送到消费者(Push模式)或者消费者主动向消息服务器拉去(Pull模式),从而实现消息生产者与消息消费者解耦。为了避免消息服务器的单点故障导致的整个系统瘫痪,通常会部署多台消息服务器共同承担消息的存储。那消息生产者如何知道消息要发送到哪台消息服务器呢?如果某一台消息服务器宕机了,那么消息生产者如何在不重启服务情况下感知呢?
    NameServer就是为了解决以上问题设计的。
    RocketMQ-03 - 图33
    Broker消息服务器在启动的时向所有NameServer注册,消息生产者(Producer)在发送消息时之前先从NameServer获取Broker服务器地址列表,然后根据负载均衡算法从列表中选择一台服务器进行发送。NameServer与每台Broker保持长连接,并间隔30S检测Broker是否存活,如果检测到Broker宕机,则从路由注册表中删除。但是路由变化不会马上通知消息生产者。这样设计的目的是为了降低NameServer实现的复杂度,在消息发送端提供容错机制保证消息发送的可用性。
    NameServer本身的高可用是通过部署多台NameServer来实现,但彼此之间不通讯,也就是NameServer服务器之间在某一个时刻的数据并不完全相同,但这对消息发送并不会造成任何影响,这也是NameServer设计的一个亮点,总之,RocketMQ设计追求简单高效。

    2.2.2 启动流程

    RocketMQ-03 - 图34
    启动类:org.apache.rocketmq.namesrv.NamesrvStartup
    ####步骤一
    解析配置文件,填充NameServerConfig、NettyServerConfig属性值,并创建NamesrvController
    代码:NamesrvController#createNamesrvController

    1. //创建NamesrvConfig
    2. final NamesrvConfig namesrvConfig = new NamesrvConfig();
    3. //创建NettyServerConfig
    4. final NettyServerConfig nettyServerConfig = new NettyServerConfig();
    5. //设置启动端口号
    6. nettyServerConfig.setListenPort(9876);
    7. //解析启动-c参数
    8. if (commandLine.hasOption('c')) {
    9. String file = commandLine.getOptionValue('c');
    10. if (file != null) {
    11. InputStream in = new BufferedInputStream(new FileInputStream(file));
    12. properties = new Properties();
    13. properties.load(in);
    14. MixAll.properties2Object(properties, namesrvConfig);
    15. MixAll.properties2Object(properties, nettyServerConfig);
    16. namesrvConfig.setConfigStorePath(file);
    17. System.out.printf("load config properties file OK, %s%n", file);
    18. in.close();
    19. }
    20. }
    21. //解析启动-p参数
    22. if (commandLine.hasOption('p')) {
    23. InternalLogger console = InternalLoggerFactory.getLogger(LoggerName.NAMESRV_CONSOLE_NAME);
    24. MixAll.printObjectProperties(console, namesrvConfig);
    25. MixAll.printObjectProperties(console, nettyServerConfig);
    26. System.exit(0);
    27. }
    28. //将启动参数填充到namesrvConfig,nettyServerConfig
    29. MixAll.properties2Object(ServerUtil.commandLine2Properties(commandLine), namesrvConfig);
    30. //创建NameServerController
    31. final NamesrvController controller = new NamesrvController(namesrvConfig, nettyServerConfig);

    NamesrvConfig属性

    1. private String rocketmqHome = System.getProperty(MixAll.ROCKETMQ_HOME_PROPERTY, System.getenv(MixAll.ROCKETMQ_HOME_ENV));
    2. private String kvConfigPath = System.getProperty("user.home") + File.separator + "namesrv" + File.separator + "kvConfig.json";
    3. private String configStorePath = System.getProperty("user.home") + File.separator + "namesrv" + File.separator + "namesrv.properties";
    4. private String productEnvName = "center";
    5. private boolean clusterTest = false;
    6. private boolean orderMessageEnable = false;

    rocketmqHome:rocketmq主目录
    kvConfig:NameServer存储KV配置属性的持久化路径
    configStorePath:nameServer默认配置文件路径
    orderMessageEnable:是否支持顺序消息
    NettyServerConfig属性

    1. private int listenPort = 8888;
    2. private int serverWorkerThreads = 8;
    3. private int serverCallbackExecutorThreads = 0;
    4. private int serverSelectorThreads = 3;
    5. private int serverOnewaySemaphoreValue = 256;
    6. private int serverAsyncSemaphoreValue = 64;
    7. private int serverChannelMaxIdleTimeSeconds = 120;
    8. private int serverSocketSndBufSize = NettySystemConfig.socketSndbufSize;
    9. private int serverSocketRcvBufSize = NettySystemConfig.socketRcvbufSize;
    10. private boolean serverPooledByteBufAllocatorEnable = true;
    11. private boolean useEpollNativeSelector = false;

    listenPort:NameServer监听端口,该值默认会被初始化为9876
    serverWorkerThreads:Netty业务线程池线程个数
    serverCallbackExecutorThreads:Netty public任务线程池线程个数,Netty网络设计,根据业务类型会创建不同的线程池,比如处理消息发送、消息消费、心跳检测等。如果该业务类型未注册线程池,则由public线程池执行。
    serverSelectorThreads:IO线程池个数,主要是NameServer、Broker端解析请求、返回相应的线程个数,这类线程主要是处理网路请求的,解析请求包,然后转发到各个业务线程池完成具体的操作,然后将结果返回给调用方;
    serverOnewaySemaphoreValue:send oneway消息请求并发读(Broker端参数);
    serverAsyncSemaphoreValue:异步消息发送最大并发度;
    serverChannelMaxIdleTimeSeconds :网络连接最大的空闲时间,默认120s。
    serverSocketSndBufSize:网络socket发送缓冲区大小。
    serverSocketRcvBufSize: 网络接收端缓存区大小。
    serverPooledByteBufAllocatorEnable:ByteBuffer是否开启缓存;
    useEpollNativeSelector:是否启用Epoll IO模型。

    步骤二

    根据启动属性创建NamesrvController实例,并初始化该实例。NameServerController实例为NameServer核心控制器
    代码:NamesrvController#initialize

    1. public boolean initialize() {
    2. //加载KV配置
    3. this.kvConfigManager.load();
    4. //创建NettyServer网络处理对象
    5. this.remotingServer = new NettyRemotingServer(this.nettyServerConfig, this.brokerHousekeepingService);
    6. //开启定时任务:每隔10s扫描一次Broker,移除不活跃的Broker
    7. this.remotingExecutor =
    8. Executors.newFixedThreadPool(nettyServerConfig.getServerWorkerThreads(), new ThreadFactoryImpl("RemotingExecutorThread_"));
    9. this.registerProcessor();
    10. this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
    11. @Override
    12. public void run() {
    13. NamesrvController.this.routeInfoManager.scanNotActiveBroker();
    14. }
    15. }, 5, 10, TimeUnit.SECONDS);
    16. //开启定时任务:每隔10min打印一次KV配置
    17. this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
    18. @Override
    19. public void run() {
    20. NamesrvController.this.kvConfigManager.printAllPeriodically();
    21. }
    22. }, 1, 10, TimeUnit.MINUTES);
    23. return true;
    24. }

    步骤三

    在JVM进程关闭之前,先将线程池关闭,及时释放资源
    代码:NamesrvStartup#start

    1. //注册JVM钩子函数代码
    2. Runtime.getRuntime().addShutdownHook(new ShutdownHookThread(log, new Callable<Void>() {
    3. @Override
    4. public Void call() throws Exception {
    5. //释放资源
    6. controller.shutdown();
    7. return null;
    8. }
    9. }));

    2.2.3 路由管理

    NameServer的主要作用是为消息的生产者和消息消费者提供关于主题Topic的路由信息,那么NameServer需要存储路由的基础信息,还要管理Broker节点,包括路由注册、路由删除等。

    2.2.3.1 路由元信息

    代码:RouteInfoManager

    1. private final HashMap<String/* topic */, List<QueueData>> topicQueueTable;
    2. private final HashMap<String/* brokerName */, BrokerData> brokerAddrTable;
    3. private final HashMap<String/* clusterName */, Set<String/* brokerName */>> clusterAddrTable;
    4. private final HashMap<String/* brokerAddr */, BrokerLiveInfo> brokerLiveTable;
    5. private final HashMap<String/* brokerAddr */, List<String>/* Filter Server */> filterServerTable;

    RocketMQ-03 - 图35
    topicQueueTable:Topic消息队列路由信息,消息发送时根据路由表进行负载均衡
    brokerAddrTable:Broker基础信息,包括brokerName、所属集群名称、主备Broker地址
    clusterAddrTable:Broker集群信息,存储集群中所有Broker名称
    brokerLiveTable:Broker状态信息,NameServer每次收到心跳包是会替换该信息
    filterServerTable:Broker上的FilterServer列表,用于类模式消息过滤。

    RocketMQ基于定于发布机制,一个Topic拥有多个消息队列,一个Broker为每一个主题创建4个读队列和4个写队列。多个Broker组成一个集群,集群由相同的多台Broker组成Master-Slave架构,brokerId为0代表Master,大于0为Slave。BrokerLiveInfo中的lastUpdateTimestamp存储上次收到Broker心跳包的时间。

RocketMQ-03 - 图36
RocketMQ-03 - 图37

2.2.3.2 路由注册

1)发送心跳包
RocketMQ-03 - 图38
RocketMQ路由注册是通过Broker与NameServer的心跳功能实现的。Broker启动时向集群中所有的NameServer发送心跳信息,每隔30s向集群中所有NameServer发送心跳包,NameServer收到心跳包时会更新brokerLiveTable缓存中BrokerLiveInfo的lastUpdataTimeStamp信息,然后NameServer每隔10s扫描brokerLiveTable,如果连续120S没有收到心跳包,NameServer将移除Broker的路由信息同时关闭Socket连接。
代码:BrokerController#start
  1. //注册Broker信息
  2. this.registerBrokerAll(true, false, true);
  3. //每隔30s上报Broker信息到NameServer
  4. this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
  5. @Override
  6. public void run() {
  7. try {
  8. BrokerController.this.registerBrokerAll(true, false, brokerConfig.isForceRegister());
  9. } catch (Throwable e) {
  10. log.error("registerBrokerAll Exception", e);
  11. }
  12. }
  13. }, 1000 * 10, Math.max(10000, Math.min(brokerConfig.getRegisterNameServerPeriod(), 60000)),
  14. TimeUnit.MILLISECONDS);

代码:BrokerOuterAPI#registerBrokerAll

  1. //获得nameServer地址信息
  2. List<String> nameServerAddressList = this.remotingClient.getNameServerAddressList();
  3. //遍历所有nameserver列表
  4. if (nameServerAddressList != null && nameServerAddressList.size() > 0) {
  5. //封装请求头
  6. final RegisterBrokerRequestHeader requestHeader = new RegisterBrokerRequestHeader();
  7. requestHeader.setBrokerAddr(brokerAddr);
  8. requestHeader.setBrokerId(brokerId);
  9. requestHeader.setBrokerName(brokerName);
  10. requestHeader.setClusterName(clusterName);
  11. requestHeader.setHaServerAddr(haServerAddr);
  12. requestHeader.setCompressed(compressed);
  13. //封装请求体
  14. RegisterBrokerBody requestBody = new RegisterBrokerBody();
  15. requestBody.setTopicConfigSerializeWrapper(topicConfigWrapper);
  16. requestBody.setFilterServerList(filterServerList);
  17. final byte[] body = requestBody.encode(compressed);
  18. final int bodyCrc32 = UtilAll.crc32(body);
  19. requestHeader.setBodyCrc32(bodyCrc32);
  20. final CountDownLatch countDownLatch = new CountDownLatch(nameServerAddressList.size());
  21. for (final String namesrvAddr : nameServerAddressList) {
  22. brokerOuterExecutor.execute(new Runnable() {
  23. @Override
  24. public void run() {
  25. try {
  26. //分别向NameServer注册
  27. RegisterBrokerResult result = registerBroker(namesrvAddr,oneway, timeoutMills,requestHeader,body);
  28. if (result != null) {
  29. registerBrokerResultList.add(result);
  30. }
  31. log.info("register broker[{}]to name server {} OK", brokerId, namesrvAddr);
  32. } catch (Exception e) {
  33. log.warn("registerBroker Exception, {}", namesrvAddr, e);
  34. } finally {
  35. countDownLatch.countDown();
  36. }
  37. }
  38. });
  39. }
  40. try {
  41. countDownLatch.await(timeoutMills, TimeUnit.MILLISECONDS);
  42. } catch (InterruptedException e) {
  43. }
  44. }

代码:BrokerOutAPI#registerBroker

  1. if (oneway) {
  2. try {
  3. this.remotingClient.invokeOneway(namesrvAddr, request, timeoutMills);
  4. } catch (RemotingTooMuchRequestException e) {
  5. // Ignore
  6. }
  7. return null;
  8. }
  9. RemotingCommand response = this.remotingClient.invokeSync(namesrvAddr, request, timeoutMills);

2)处理心跳包

RocketMQ-03 - 图39
org.apache.rocketmq.namesrv.processor.DefaultRequestProcessor网路处理类解析请求类型,如果请求类型是为REGISTER_BROKER,则将请求转发到RouteInfoManager#regiesterBroker
代码:DefaultRequestProcessor#processRequest

  1. //判断是注册Broker信息
  2. case RequestCode.REGISTER_BROKER:
  3. Version brokerVersion = MQVersion.value2Version(request.getVersion());
  4. if (brokerVersion.ordinal() >= MQVersion.Version.V3_0_11.ordinal()) {
  5. return this.registerBrokerWithFilterServer(ctx, request);
  6. } else {
  7. //注册Broker信息
  8. return this.registerBroker(ctx, request);
  9. }

代码:DefaultRequestProcessor#registerBroker

  1. RegisterBrokerResult result = this.namesrvController.getRouteInfoManager().registerBroker(
  2. requestHeader.getClusterName(),
  3. requestHeader.getBrokerAddr(),
  4. requestHeader.getBrokerName(),
  5. requestHeader.getBrokerId(),
  6. requestHeader.getHaServerAddr(),
  7. topicConfigWrapper,
  8. null,
  9. ctx.channel()
  10. );

代码:RouteInfoManager#registerBroker
维护路由信息

  1. //加锁
  2. this.lock.writeLock().lockInterruptibly();
  3. //维护clusterAddrTable
  4. Set<String> brokerNames = this.clusterAddrTable.get(clusterName);
  5. if (null == brokerNames) {
  6. brokerNames = new HashSet<String>();
  7. this.clusterAddrTable.put(clusterName, brokerNames);
  8. }
  9. brokerNames.add(brokerName);
  1. //维护brokerAddrTable
  2. BrokerData brokerData = this.brokerAddrTable.get(brokerName);
  3. //第一次注册,则创建brokerData
  4. if (null == brokerData) {
  5. registerFirst = true;
  6. brokerData = new BrokerData(clusterName, brokerName, new HashMap<Long, String>());
  7. this.brokerAddrTable.put(brokerName, brokerData);
  8. }
  9. //非第一次注册,更新Broker
  10. Map<Long, String> brokerAddrsMap = brokerData.getBrokerAddrs();
  11. Iterator<Entry<Long, String>> it = brokerAddrsMap.entrySet().iterator();
  12. while (it.hasNext()) {
  13. Entry<Long, String> item = it.next();
  14. if (null != brokerAddr && brokerAddr.equals(item.getValue()) && brokerId != item.getKey()) {
  15. it.remove();
  16. }
  17. }
  18. String oldAddr = brokerData.getBrokerAddrs().put(brokerId, brokerAddr);
  19. registerFirst = registerFirst || (null == oldAddr);
  1. //维护topicQueueTable
  2. if (null != topicConfigWrapper && MixAll.MASTER_ID == brokerId) {
  3. if (this.isBrokerTopicConfigChanged(brokerAddr, topicConfigWrapper.getDataVersion()) ||
  4. registerFirst) {
  5. ConcurrentMap<String, TopicConfig> tcTable = topicConfigWrapper.getTopicConfigTable();
  6. if (tcTable != null) {
  7. for (Map.Entry<String, TopicConfig> entry : tcTable.entrySet()) {
  8. this.createAndUpdateQueueData(brokerName, entry.getValue());
  9. }
  10. }
  11. }
  12. }

代码:RouteInfoManager#createAndUpdateQueueData

  1. private void createAndUpdateQueueData(final String brokerName, final TopicConfig topicConfig) {
  2. //创建QueueData
  3. QueueData queueData = new QueueData();
  4. queueData.setBrokerName(brokerName);
  5. queueData.setWriteQueueNums(topicConfig.getWriteQueueNums());
  6. queueData.setReadQueueNums(topicConfig.getReadQueueNums());
  7. queueData.setPerm(topicConfig.getPerm());
  8. queueData.setTopicSynFlag(topicConfig.getTopicSysFlag());
  9. //获得topicQueueTable中队列集合
  10. List<QueueData> queueDataList = this.topicQueueTable.get(topicConfig.getTopicName());
  11. //topicQueueTable为空,则直接添加queueData到队列集合
  12. if (null == queueDataList) {
  13. queueDataList = new LinkedList<QueueData>();
  14. queueDataList.add(queueData);
  15. this.topicQueueTable.put(topicConfig.getTopicName(), queueDataList);
  16. log.info("new topic registered, {} {}", topicConfig.getTopicName(), queueData);
  17. } else {
  18. //判断是否是新的队列
  19. boolean addNewOne = true;
  20. Iterator<QueueData> it = queueDataList.iterator();
  21. while (it.hasNext()) {
  22. QueueData qd = it.next();
  23. //如果brokerName相同,代表不是新的队列
  24. if (qd.getBrokerName().equals(brokerName)) {
  25. if (qd.equals(queueData)) {
  26. addNewOne = false;
  27. } else {
  28. log.info("topic changed, {} OLD: {} NEW: {}", topicConfig.getTopicName(), qd,
  29. queueData);
  30. it.remove();
  31. }
  32. }
  33. }
  34. //如果是新的队列,则添加队列到queueDataList
  35. if (addNewOne) {
  36. queueDataList.add(queueData);
  37. }
  38. }
  39. }
  1. //维护brokerLiveTable
  2. BrokerLiveInfo prevBrokerLiveInfo = this.brokerLiveTable.put(brokerAddr,new BrokerLiveInfo(
  3. System.currentTimeMillis(),
  4. topicConfigWrapper.getDataVersion(),
  5. channel,
  6. haServerAddr));
  1. //维护filterServerList
  2. if (filterServerList != null) {
  3. if (filterServerList.isEmpty()) {
  4. this.filterServerTable.remove(brokerAddr);
  5. } else {
  6. this.filterServerTable.put(brokerAddr, filterServerList);
  7. }
  8. }
  9. if (MixAll.MASTER_ID != brokerId) {
  10. String masterAddr = brokerData.getBrokerAddrs().get(MixAll.MASTER_ID);
  11. if (masterAddr != null) {
  12. BrokerLiveInfo brokerLiveInfo = this.brokerLiveTable.get(masterAddr);
  13. if (brokerLiveInfo != null) {
  14. result.setHaServerAddr(brokerLiveInfo.getHaServerAddr());
  15. result.setMasterAddr(masterAddr);
  16. }
  17. }
  18. }

2.2.3.3 路由删除

Broker每隔30s向NameServer发送一个心跳包,心跳包包含BrokerIdBroker地址,Broker名称,Broker所属集群名称、Broker关联的FilterServer列表。但是如果Broker宕机,NameServer无法收到心跳包,此时NameServer如何来剔除这些失效的Broker呢?NameServer会每隔10s扫描brokerLiveTable状态表,如果BrokerLivelastUpdateTimestamp的时间戳距当前时间超过120s,则认为Broker失效,移除该Broker,关闭与Broker连接,同时更新topicQueueTablebrokerAddrTablebrokerLiveTablefilterServerTable
RocketMQ有两个触发点来删除路由信息

  • NameServer定期扫描brokerLiveTable检测上次心跳包与当前系统的时间差,如果时间超过120s,则需要移除broker。
  • Broker在正常关闭的情况下,会执行unregisterBroker指令

这两种方式路由删除的方法都是一样的,就是从相关路由表中删除与该broker相关的信息。
RocketMQ-03 - 图40
代码:NamesrvController#initialize

  1. //每隔10s扫描一次为活跃Broker
  2. this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
  3. @Override
  4. public void run() {
  5. NamesrvController.this.routeInfoManager.scanNotActiveBroker();
  6. }
  7. }, 5, 10, TimeUnit.SECONDS);

代码:RouteInfoManager#scanNotActiveBroker

  1. public void scanNotActiveBroker() {
  2. //获得brokerLiveTable
  3. Iterator<Entry<String, BrokerLiveInfo>> it = this.brokerLiveTable.entrySet().iterator();
  4. //遍历brokerLiveTable
  5. while (it.hasNext()) {
  6. Entry<String, BrokerLiveInfo> next = it.next();
  7. long last = next.getValue().getLastUpdateTimestamp();
  8. //如果收到心跳包的时间距当时时间是否超过120s
  9. if ((last + BROKER_CHANNEL_EXPIRED_TIME) < System.currentTimeMillis()) {
  10. //关闭连接
  11. RemotingUtil.closeChannel(next.getValue().getChannel());
  12. //移除broker
  13. it.remove();
  14. //维护路由表
  15. this.onChannelDestroy(next.getKey(), next.getValue().getChannel());
  16. }
  17. }
  18. }

代码:RouteInfoManager#onChannelDestroy

  1. //申请写锁,根据brokerAddress从brokerLiveTable和filterServerTable移除
  2. this.lock.writeLock().lockInterruptibly();
  3. this.brokerLiveTable.remove(brokerAddrFound);
  4. this.filterServerTable.remove(brokerAddrFound);
  1. //维护brokerAddrTable
  2. String brokerNameFound = null;
  3. boolean removeBrokerName = false;
  4. Iterator<Entry<String, BrokerData>> itBrokerAddrTable =this.brokerAddrTable.entrySet().iterator();
  5. //遍历brokerAddrTable
  6. while (itBrokerAddrTable.hasNext() && (null == brokerNameFound)) {
  7. BrokerData brokerData = itBrokerAddrTable.next().getValue();
  8. //遍历broker地址
  9. Iterator<Entry<Long, String>> it = brokerData.getBrokerAddrs().entrySet().iterator();
  10. while (it.hasNext()) {
  11. Entry<Long, String> entry = it.next();
  12. Long brokerId = entry.getKey();
  13. String brokerAddr = entry.getValue();
  14. //根据broker地址移除brokerAddr
  15. if (brokerAddr.equals(brokerAddrFound)) {
  16. brokerNameFound = brokerData.getBrokerName();
  17. it.remove();
  18. log.info("remove brokerAddr[{}, {}] from brokerAddrTable, because channel destroyed",
  19. brokerId, brokerAddr);
  20. break;
  21. }
  22. }
  23. //如果当前主题只包含待移除的broker,则移除该topic
  24. if (brokerData.getBrokerAddrs().isEmpty()) {
  25. removeBrokerName = true;
  26. itBrokerAddrTable.remove();
  27. log.info("remove brokerName[{}] from brokerAddrTable, because channel destroyed",
  28. brokerData.getBrokerName());
  29. }
  30. }
  1. //维护clusterAddrTable
  2. if (brokerNameFound != null && removeBrokerName) {
  3. Iterator<Entry<String, Set<String>>> it = this.clusterAddrTable.entrySet().iterator();
  4. //遍历clusterAddrTable
  5. while (it.hasNext()) {
  6. Entry<String, Set<String>> entry = it.next();
  7. //获得集群名称
  8. String clusterName = entry.getKey();
  9. //获得集群中brokerName集合
  10. Set<String> brokerNames = entry.getValue();
  11. //从brokerNames中移除brokerNameFound
  12. boolean removed = brokerNames.remove(brokerNameFound);
  13. if (removed) {
  14. log.info("remove brokerName[{}], clusterName[{}] from clusterAddrTable, because channel destroyed",
  15. brokerNameFound, clusterName);
  16. if (brokerNames.isEmpty()) {
  17. log.info("remove the clusterName[{}] from clusterAddrTable, because channel destroyed and no broker in this cluster",
  18. clusterName);
  19. //如果集群中不包含任何broker,则移除该集群
  20. it.remove();
  21. }
  22. break;
  23. }
  24. }
  25. }
  1. //维护topicQueueTable队列
  2. if (removeBrokerName) {
  3. //遍历topicQueueTable
  4. Iterator<Entry<String, List<QueueData>>> itTopicQueueTable =
  5. this.topicQueueTable.entrySet().iterator();
  6. while (itTopicQueueTable.hasNext()) {
  7. Entry<String, List<QueueData>> entry = itTopicQueueTable.next();
  8. //主题名称
  9. String topic = entry.getKey();
  10. //队列集合
  11. List<QueueData> queueDataList = entry.getValue();
  12. //遍历该主题队列
  13. Iterator<QueueData> itQueueData = queueDataList.iterator();
  14. while (itQueueData.hasNext()) {
  15. //从队列中移除为活跃broker信息
  16. QueueData queueData = itQueueData.next();
  17. if (queueData.getBrokerName().equals(brokerNameFound)) {
  18. itQueueData.remove();
  19. log.info("remove topic[{} {}], from topicQueueTable, because channel destroyed",
  20. topic, queueData);
  21. }
  22. }
  23. //如果该topic的队列为空,则移除该topic
  24. if (queueDataList.isEmpty()) {
  25. itTopicQueueTable.remove();
  26. log.info("remove topic[{}] all queue, from topicQueueTable, because channel destroyed",
  27. topic);
  28. }
  29. }
  30. }
  1. //释放写锁
  2. finally {
  3. this.lock.writeLock().unlock();
  4. }

2.2.3.4 路由发现

RocketMQ路由发现是非实时的,当Topic路由出现变化后,NameServer不会主动推送给客户端,而是由客户端定时拉取主题最新的路由。
代码:DefaultRequestProcessor#getRouteInfoByTopic

  1. public RemotingCommand getRouteInfoByTopic(ChannelHandlerContext ctx,
  2. RemotingCommand request) throws RemotingCommandException {
  3. final RemotingCommand response = RemotingCommand.createResponseCommand(null);
  4. final GetRouteInfoRequestHeader requestHeader =
  5. (GetRouteInfoRequestHeader) request.decodeCommandCustomHeader(GetRouteInfoRequestHeader.class);
  6. //调用RouteInfoManager的方法,从路由表topicQueueTable、brokerAddrTable、filterServerTable中分别填充TopicRouteData的List<QueueData>、List<BrokerData>、filterServer
  7. TopicRouteData topicRouteData = this.namesrvController.getRouteInfoManager().pickupTopicRouteData(requestHeader.getTopic());
  8. //如果找到主题对应你的路由信息并且该主题为顺序消息,则从NameServer KVConfig中获取关于顺序消息相关的配置填充路由信息
  9. if (topicRouteData != null) {
  10. if (this.namesrvController.getNamesrvConfig().isOrderMessageEnable()) {
  11. String orderTopicConf =
  12. this.namesrvController.getKvConfigManager().getKVConfig(NamesrvUtil.NAMESPACE_ORDER_TOPIC_CONFIG,
  13. requestHeader.getTopic());
  14. topicRouteData.setOrderTopicConf(orderTopicConf);
  15. }
  16. byte[] content = topicRouteData.encode();
  17. response.setBody(content);
  18. response.setCode(ResponseCode.SUCCESS);
  19. response.setRemark(null);
  20. return response;
  21. }
  22. response.setCode(ResponseCode.TOPIC_NOT_EXIST);
  23. response.setRemark("No topic route info in name server for the topic: " + requestHeader.getTopic()
  24. + FAQUrl.suggestTodo(FAQUrl.APPLY_TOPIC_URL));
  25. return response;
  26. }

2.2.4 小结

RocketMQ-03 - 图41

2.3 Producer

消息生产者的代码都在client模块中,相对于RocketMQ来讲,消息生产者就是客户端,也是消息的提供者。
RocketMQ-03 - 图42
###2.3.1 方法和属性
####1)主要方法介绍
RocketMQ-03 - 图43

  1. //创建主题
  2. void createTopic(final String key, final String newTopic, final int queueNum) throws MQClientException;
  1. //根据时间戳从队列中查找消息偏移量
  2. long searchOffset(final MessageQueue mq, final long timestamp)
  1. //查找消息队列中最大的偏移量
  2. long maxOffset(final MessageQueue mq) throws MQClientException;
  1. //查找消息队列中最小的偏移量
  2. long minOffset(final MessageQueue mq)
  1. //根据偏移量查找消息
  2. MessageExt viewMessage(final String offsetMsgId) throws RemotingException, MQBrokerException,
  3. InterruptedException, MQClientException;
  1. //根据条件查找消息
  2. QueryResult queryMessage(final String topic, final String key, final int maxNum, final long begin,
  3. final long end) throws MQClientException, InterruptedException;
  1. //根据消息ID和主题查找消息
  2. MessageExt viewMessage(String topic,String msgId) throws RemotingException, MQBrokerException, InterruptedException, MQClientException;

RocketMQ-03 - 图44

  1. //启动
  2. void start() throws MQClientException;
  1. //关闭
  2. void shutdown();
  1. //查找该主题下所有消息
  2. List<MessageQueue> fetchPublishMessageQueues(final String topic) throws MQClientException;
  1. //同步发送消息
  2. SendResult send(final Message msg) throws MQClientException, RemotingException, MQBrokerException,
  3. InterruptedException;
  1. //同步超时发送消息
  2. SendResult send(final Message msg, final long timeout) throws MQClientException,
  3. RemotingException, MQBrokerException, InterruptedException;
  1. //异步发送消息
  2. void send(final Message msg, final SendCallback sendCallback) throws MQClientException,
  3. RemotingException, InterruptedException;
  1. //异步超时发送消息
  2. void send(final Message msg, final SendCallback sendCallback, final long timeout)
  3. throws MQClientException, RemotingException, InterruptedException;
  1. //发送单向消息
  2. void sendOneway(final Message msg) throws MQClientException, RemotingException,
  3. InterruptedException;
  1. //选择指定队列同步发送消息
  2. SendResult send(final Message msg, final MessageQueue mq) throws MQClientException,
  3. RemotingException, MQBrokerException, InterruptedException;
  1. //选择指定队列异步发送消息
  2. void send(final Message msg, final MessageQueue mq, final SendCallback sendCallback)
  3. throws MQClientException, RemotingException, InterruptedException;
  1. //选择指定队列单项发送消息
  2. void sendOneway(final Message msg, final MessageQueue mq) throws MQClientException,
  3. RemotingException, InterruptedException;
  1. //批量发送消息
  2. SendResult send(final Collection<Message> msgs) throws MQClientException, RemotingException, MQBrokerException,InterruptedException;

2)属性介绍
RocketMQ-03 - 图45

  1. producerGroup:生产者所属组
  2. createTopicKey:默认Topic
  3. defaultTopicQueueNums:默认主题在每一个Broker队列数量
  4. sendMsgTimeout:发送消息默认超时时间,默认3s
  5. compressMsgBodyOverHowmuch:消息体超过该值则启用压缩,默认4k
  6. retryTimesWhenSendFailed:同步方式发送消息重试次数,默认为2,总共执行3
  7. retryTimesWhenSendAsyncFailed:异步方法发送消息重试次数,默认为2
  8. retryAnotherBrokerWhenNotStoreOK:消息重试时选择另外一个Broker时,是否不等待存储结果就返回,默认为false
  9. maxMessageSize:允许发送的最大消息长度,默认为4M

2.3.2 启动流程

RocketMQ-03 - 图46
代码:DefaultMQProducerImpl#start

  1. //检查生产者组是否满足要求
  2. this.checkConfig();
  3. //更改当前instanceName为进程ID
  4. if (!this.defaultMQProducer.getProducerGroup().equals(MixAll.CLIENT_INNER_PRODUCER_GROUP)) {
  5. this.defaultMQProducer.changeInstanceNameToPID();
  6. }
  7. //获得MQ客户端实例
  8. this.mQClientFactory = MQClientManager.getInstance().getAndCreateMQClientInstance(this.defaultMQProducer, rpcHook);

整个JVM中只存在一个MQClientManager实例,维护一个MQClientInstance缓存表 ConcurrentMap factoryTable = new ConcurrentHashMap(); 同一个clientId只会创建一个MQClientInstance。 MQClientInstance封装了RocketMQ网络处理API,是消息生产者和消息消费者与NameServer、Broker打交道的网络通道

代码:MQClientManager#getAndCreateMQClientInstance

  1. public MQClientInstance getAndCreateMQClientInstance(final ClientConfig clientConfig,
  2. RPCHook rpcHook) {
  3. //构建客户端ID
  4. String clientId = clientConfig.buildMQClientId();
  5. //根据客户端ID或者客户端实例
  6. MQClientInstance instance = this.factoryTable.get(clientId);
  7. //实例如果为空就创建新的实例,并添加到实例表中
  8. if (null == instance) {
  9. instance =
  10. new MQClientInstance(clientConfig.cloneClientConfig(),
  11. this.factoryIndexGenerator.getAndIncrement(), clientId, rpcHook);
  12. MQClientInstance prev = this.factoryTable.putIfAbsent(clientId, instance);
  13. if (prev != null) {
  14. instance = prev;
  15. log.warn("Returned Previous MQClientInstance for clientId:[{}]", clientId);
  16. } else {
  17. log.info("Created new MQClientInstance for clientId:[{}]", clientId);
  18. }
  19. }
  20. return instance;
  21. }

代码:DefaultMQProducerImpl#start

  1. //注册当前生产者到到MQClientInstance管理中,方便后续调用网路请求
  2. boolean registerOK = mQClientFactory.registerProducer(this.defaultMQProducer.getProducerGroup(), this);
  3. if (!registerOK) {
  4. this.serviceState = ServiceState.CREATE_JUST;
  5. throw new MQClientException("The producer group[" + this.defaultMQProducer.getProducerGroup()
  6. + "] has been created before, specify another name please." + FAQUrl.suggestTodo(FAQUrl.GROUP_NAME_DUPLICATE_URL),
  7. null);
  8. }
  9. //启动生产者
  10. if (startFactory) {
  11. mQClientFactory.start();
  12. }

2.3.3 消息发送

RocketMQ-03 - 图47
代码:DefaultMQProducerImpl#send(Message msg)

  1. //发送消息
  2. public SendResult send(Message msg) {
  3. return send(msg, this.defaultMQProducer.getSendMsgTimeout());
  4. }

代码:DefaultMQProducerImpl#send(Message msg,long timeout)

  1. //发送消息,默认超时时间为3s
  2. public SendResult send(Message msg,long timeout){
  3. return this.sendDefaultImpl(msg, CommunicationMode.SYNC, null, timeout);
  4. }

代码:DefaultMQProducerImpl#sendDefaultImpl

  1. //校验消息
  2. Validators.checkMessage(msg, this.defaultMQProducer);

1)验证消息
代码:Validators#checkMessage

  1. public static void checkMessage(Message msg, DefaultMQProducer defaultMQProducer)
  2. throws MQClientException {
  3. //判断是否为空
  4. if (null == msg) {
  5. throw new MQClientException(ResponseCode.MESSAGE_ILLEGAL, "the message is null");
  6. }
  7. // 校验主题
  8. Validators.checkTopic(msg.getTopic());
  9. // 校验消息体
  10. if (null == msg.getBody()) {
  11. throw new MQClientException(ResponseCode.MESSAGE_ILLEGAL, "the message body is null");
  12. }
  13. if (0 == msg.getBody().length) {
  14. throw new MQClientException(ResponseCode.MESSAGE_ILLEGAL, "the message body length is zero");
  15. }
  16. if (msg.getBody().length > defaultMQProducer.getMaxMessageSize()) {
  17. throw new MQClientException(ResponseCode.MESSAGE_ILLEGAL,
  18. "the message body size over max value, MAX: " + defaultMQProducer.getMaxMessageSize());
  19. }
  20. }

2)查找路由
代码:DefaultMQProducerImpl#tryToFindTopicPublishInfo

  1. private TopicPublishInfo tryToFindTopicPublishInfo(final String topic) {
  2. //从缓存中获得主题的路由信息
  3. TopicPublishInfo topicPublishInfo = this.topicPublishInfoTable.get(topic);
  4. //路由信息为空,则从NameServer获取路由
  5. if (null == topicPublishInfo || !topicPublishInfo.ok()) {
  6. this.topicPublishInfoTable.putIfAbsent(topic, new TopicPublishInfo());
  7. this.mQClientFactory.updateTopicRouteInfoFromNameServer(topic);
  8. topicPublishInfo = this.topicPublishInfoTable.get(topic);
  9. }
  10. if (topicPublishInfo.isHaveTopicRouterInfo() || topicPublishInfo.ok()) {
  11. return topicPublishInfo;
  12. } else {
  13. //如果未找到当前主题的路由信息,则用默认主题继续查找
  14. this.mQClientFactory.updateTopicRouteInfoFromNameServer(topic, true, this.defaultMQProducer);
  15. topicPublishInfo = this.topicPublishInfoTable.get(topic);
  16. return topicPublishInfo;
  17. }
  18. }

RocketMQ-03 - 图48
代码:TopicPublishInfo

  1. public class TopicPublishInfo {
  2. private boolean orderTopic = false; //是否是顺序消息
  3. private boolean haveTopicRouterInfo = false;
  4. private List<MessageQueue> messageQueueList = new ArrayList<MessageQueue>(); //该主题消息队列
  5. private volatile ThreadLocalIndex sendWhichQueue = new ThreadLocalIndex();//每选择一次消息队列,该值+1
  6. private TopicRouteData topicRouteData;//关联Topic路由元信息
  7. }

代码:MQClientInstance#updateTopicRouteInfoFromNameServer

  1. TopicRouteData topicRouteData;
  2. //使用默认主题从NameServer获取路由信息
  3. if (isDefault && defaultMQProducer != null) {
  4. topicRouteData = this.mQClientAPIImpl.getDefaultTopicRouteInfoFromNameServer(defaultMQProducer.getCreateTopicKey(),
  5. 1000 * 3);
  6. if (topicRouteData != null) {
  7. for (QueueData data : topicRouteData.getQueueDatas()) {
  8. int queueNums = Math.min(defaultMQProducer.getDefaultTopicQueueNums(), data.getReadQueueNums());
  9. data.setReadQueueNums(queueNums);
  10. data.setWriteQueueNums(queueNums);
  11. }
  12. }
  13. } else {
  14. //使用指定主题从NameServer获取路由信息
  15. topicRouteData = this.mQClientAPIImpl.getTopicRouteInfoFromNameServer(topic, 1000 * 3);
  16. }

代码:MQClientInstance#updateTopicRouteInfoFromNameServer

  1. //判断路由是否需要更改
  2. TopicRouteData old = this.topicRouteTable.get(topic);
  3. boolean changed = topicRouteDataIsChange(old, topicRouteData);
  4. if (!changed) {
  5. changed = this.isNeedUpdateTopicRouteInfo(topic);
  6. } else {
  7. log.info("the topic[{}] route info changed, old[{}] ,new[{}]", topic, old, topicRouteData);
  8. }

代码:MQClientInstance#updateTopicRouteInfoFromNameServer

  1. if (changed) {
  2. //将topicRouteData转换为发布队列
  3. TopicPublishInfo publishInfo = topicRouteData2TopicPublishInfo(topic, topicRouteData);
  4. publishInfo.setHaveTopicRouterInfo(true);
  5. //遍历生产
  6. Iterator<Entry<String, MQProducerInner>> it = this.producerTable.entrySet().iterator();
  7. while (it.hasNext()) {
  8. Entry<String, MQProducerInner> entry = it.next();
  9. MQProducerInner impl = entry.getValue();
  10. if (impl != null) {
  11. //生产者不为空时,更新publishInfo信息
  12. impl.updateTopicPublishInfo(topic, publishInfo);
  13. }
  14. }
  15. }

代码:MQClientInstance#topicRouteData2TopicPublishInfo

  1. public static TopicPublishInfo topicRouteData2TopicPublishInfo(final String topic, final TopicRouteData route) {
  2. //创建TopicPublishInfo对象
  3. TopicPublishInfo info = new TopicPublishInfo();
  4. //关联topicRoute
  5. info.setTopicRouteData(route);
  6. //顺序消息,更新TopicPublishInfo
  7. if (route.getOrderTopicConf() != null && route.getOrderTopicConf().length() > 0) {
  8. String[] brokers = route.getOrderTopicConf().split(";");
  9. for (String broker : brokers) {
  10. String[] item = broker.split(":");
  11. int nums = Integer.parseInt(item[1]);
  12. for (int i = 0; i < nums; i++) {
  13. MessageQueue mq = new MessageQueue(topic, item[0], i);
  14. info.getMessageQueueList().add(mq);
  15. }
  16. }
  17. info.setOrderTopic(true);
  18. } else {
  19. //非顺序消息更新TopicPublishInfo
  20. List<QueueData> qds = route.getQueueDatas();
  21. Collections.sort(qds);
  22. //遍历topic队列信息
  23. for (QueueData qd : qds) {
  24. //是否是写队列
  25. if (PermName.isWriteable(qd.getPerm())) {
  26. BrokerData brokerData = null;
  27. //遍历写队列Broker
  28. for (BrokerData bd : route.getBrokerDatas()) {
  29. //根据名称获得读队列对应的Broker
  30. if (bd.getBrokerName().equals(qd.getBrokerName())) {
  31. brokerData = bd;
  32. break;
  33. }
  34. }
  35. if (null == brokerData) {
  36. continue;
  37. }
  38. if (!brokerData.getBrokerAddrs().containsKey(MixAll.MASTER_ID)) {
  39. continue;
  40. }
  41. //封装TopicPublishInfo写队列
  42. for (int i = 0; i < qd.getWriteQueueNums(); i++) {
  43. MessageQueue mq = new MessageQueue(topic, qd.getBrokerName(), i);
  44. info.getMessageQueueList().add(mq);
  45. }
  46. }
  47. }
  48. info.setOrderTopic(false);
  49. }
  50. //返回TopicPublishInfo对象
  51. return info;
  52. }

3)选择队列

  • 默认不启用Broker故障延迟机制

代码:TopicPublishInfo#selectOneMessageQueue(lastBrokerName)

  1. public MessageQueue selectOneMessageQueue(final String lastBrokerName) {
  2. //第一次选择队列
  3. if (lastBrokerName == null) {
  4. return selectOneMessageQueue();
  5. } else {
  6. //sendWhichQueue
  7. int index = this.sendWhichQueue.getAndIncrement();
  8. //遍历消息队列集合
  9. for (int i = 0; i < this.messageQueueList.size(); i++) {
  10. //sendWhichQueue自增后取模
  11. int pos = Math.abs(index++) % this.messageQueueList.size();
  12. if (pos < 0)
  13. pos = 0;
  14. //规避上次Broker队列
  15. MessageQueue mq = this.messageQueueList.get(pos);
  16. if (!mq.getBrokerName().equals(lastBrokerName)) {
  17. return mq;
  18. }
  19. }
  20. //如果以上情况都不满足,返回sendWhichQueue取模后的队列
  21. return selectOneMessageQueue();
  22. }
  23. }

代码:TopicPublishInfo#selectOneMessageQueue()

  1. //第一次选择队列
  2. public MessageQueue selectOneMessageQueue() {
  3. //sendWhichQueue自增
  4. int index = this.sendWhichQueue.getAndIncrement();
  5. //对队列大小取模
  6. int pos = Math.abs(index) % this.messageQueueList.size();
  7. if (pos < 0)
  8. pos = 0;
  9. //返回对应的队列
  10. return this.messageQueueList.get(pos);
  11. }
  • 启用Broker故障延迟机制

    1. public MessageQueue selectOneMessageQueue(final TopicPublishInfo tpInfo, final String lastBrokerName) {
    2. //Broker故障延迟机制
    3. if (this.sendLatencyFaultEnable) {
    4. try {
    5. //对sendWhichQueue自增
    6. int index = tpInfo.getSendWhichQueue().getAndIncrement();
    7. //对消息队列轮询获取一个队列
    8. for (int i = 0; i < tpInfo.getMessageQueueList().size(); i++) {
    9. int pos = Math.abs(index++) % tpInfo.getMessageQueueList().size();
    10. if (pos < 0)
    11. pos = 0;
    12. MessageQueue mq = tpInfo.getMessageQueueList().get(pos);
    13. //验证该队列是否可用
    14. if (latencyFaultTolerance.isAvailable(mq.getBrokerName())) {
    15. //可用
    16. if (null == lastBrokerName || mq.getBrokerName().equals(lastBrokerName))
    17. return mq;
    18. }
    19. }
    20. //从规避的Broker中选择一个可用的Broker
    21. final String notBestBroker = latencyFaultTolerance.pickOneAtLeast();
    22. //获得Broker的写队列集合
    23. int writeQueueNums = tpInfo.getQueueIdByBroker(notBestBroker);
    24. if (writeQueueNums > 0) {
    25. //获得一个队列,指定broker和队列ID并返回
    26. final MessageQueue mq = tpInfo.selectOneMessageQueue();
    27. if (notBestBroker != null) {
    28. mq.setBrokerName(notBestBroker);
    29. mq.setQueueId(tpInfo.getSendWhichQueue().getAndIncrement() % writeQueueNums);
    30. }
    31. return mq;
    32. } else {
    33. latencyFaultTolerance.remove(notBestBroker);
    34. }
    35. } catch (Exception e) {
    36. log.error("Error occurred when selecting message queue", e);
    37. }
    38. return tpInfo.selectOneMessageQueue();
    39. }
    40. return tpInfo.selectOneMessageQueue(lastBrokerName);
    41. }

    RocketMQ-03 - 图49

  • 延迟机制接口规范

    1. public interface LatencyFaultTolerance<T> {
    2. //更新失败条目
    3. void updateFaultItem(final T name, final long currentLatency, final long notAvailableDuration);
    4. //判断Broker是否可用
    5. boolean isAvailable(final T name);
    6. //移除Fault条目
    7. void remove(final T name);
    8. //尝试从规避的Broker中选择一个可用的Broker
    9. T pickOneAtLeast();
    10. }
  • FaultItem:失败条目

    1. class FaultItem implements Comparable<FaultItem> {
    2. //条目唯一键,这里为brokerName
    3. private final String name;
    4. //本次消息发送延迟
    5. private volatile long currentLatency;
    6. //故障规避开始时间
    7. private volatile long startTimestamp;
    8. }
  • 消息失败策略

    1. public class MQFaultStrategy {
    2. //根据currentLatency本地消息发送延迟,从latencyMax尾部向前找到第一个比currentLatency小的索引,如果没有找到,返回0
    3. private long[] latencyMax = {50L, 100L, 550L, 1000L, 2000L, 3000L, 15000L};
    4. //根据这个索引从notAvailableDuration取出对应的时间,在该时长内,Broker设置为不可用
    5. private long[] notAvailableDuration = {0L, 0L, 30000L, 60000L, 120000L, 180000L, 600000L};
    6. }

    原理分析
    代码:DefaultMQProducerImpl#sendDefaultImpl

    1. sendResult = this.sendKernelImpl(msg,
    2. mq,
    3. communicationMode,
    4. sendCallback,
    5. topicPublishInfo,
    6. timeout - costTime);
    7. endTimestamp = System.currentTimeMillis();
    8. this.updateFaultItem(mq.getBrokerName(), endTimestamp - beginTimestampPrev, false);

    如果上述发送过程出现异常,则调用DefaultMQProducerImpl#updateFaultItem

    1. public void updateFaultItem(final String brokerName, final long currentLatency, boolean isolation) {
    2. //参数一:broker名称
    3. //参数二:本次消息发送延迟时间
    4. //参数三:是否隔离
    5. this.mqFaultStrategy.updateFaultItem(brokerName, currentLatency, isolation);
    6. }

    代码:MQFaultStrategy#updateFaultItem

    1. public void updateFaultItem(final String brokerName, final long currentLatency, boolean isolation) {
    2. if (this.sendLatencyFaultEnable) {
    3. //计算broker规避的时长
    4. long duration = computeNotAvailableDuration(isolation ? 30000 : currentLatency);
    5. //更新该FaultItem规避时长
    6. this.latencyFaultTolerance.updateFaultItem(brokerName, currentLatency, duration);
    7. }
    8. }

    代码:MQFaultStrategy#computeNotAvailableDuration

    1. private long computeNotAvailableDuration(final long currentLatency) {
    2. //遍历latencyMax
    3. for (int i = latencyMax.length - 1; i >= 0; i--) {
    4. //找到第一个比currentLatency的latencyMax值
    5. if (currentLatency >= latencyMax[i])
    6. return this.notAvailableDuration[i];
    7. }
    8. //没有找到则返回0
    9. return 0;
    10. }

    代码:LatencyFaultToleranceImpl#updateFaultItem

    1. public void updateFaultItem(final String name, final long currentLatency, final long notAvailableDuration) {
    2. //获得原FaultItem
    3. FaultItem old = this.faultItemTable.get(name);
    4. //为空新建faultItem对象,设置规避时长和开始时间
    5. if (null == old) {
    6. final FaultItem faultItem = new FaultItem(name);
    7. faultItem.setCurrentLatency(currentLatency);
    8. faultItem.setStartTimestamp(System.currentTimeMillis() + notAvailableDuration);
    9. old = this.faultItemTable.putIfAbsent(name, faultItem);
    10. if (old != null) {
    11. old.setCurrentLatency(currentLatency);
    12. old.setStartTimestamp(System.currentTimeMillis() + notAvailableDuration);
    13. }
    14. } else {
    15. //更新规避时长和开始时间
    16. old.setCurrentLatency(currentLatency);
    17. old.setStartTimestamp(System.currentTimeMillis() + notAvailableDuration);
    18. }
    19. }

    4)发送消息
    消息发送API核心入口DefaultMQProducerImpl#sendKernelImpl

    1. private SendResult sendKernelImpl(
    2. final Message msg, //待发送消息
    3. final MessageQueue mq, //消息发送队列
    4. final CommunicationMode communicationMode, //消息发送内模式
    5. final SendCallback sendCallback, pp //异步消息回调函数
    6. final TopicPublishInfo topicPublishInfo, //主题路由信息
    7. final long timeout //超时时间
    8. )

    代码:DefaultMQProducerImpl#sendKernelImpl

    1. //获得broker网络地址信息
    2. String brokerAddr = this.mQClientFactory.findBrokerAddressInPublish(mq.getBrokerName());
    3. if (null == brokerAddr) {
    4. //没有找到从NameServer更新broker网络地址信息
    5. tryToFindTopicPublishInfo(mq.getTopic());
    6. brokerAddr = this.mQClientFactory.findBrokerAddressInPublish(mq.getBrokerName());
    7. }
    1. //为消息分类唯一ID
    2. if (!(msg instanceof MessageBatch)) {
    3. MessageClientIDSetter.setUniqID(msg);
    4. }
    5. boolean topicWithNamespace = false;
    6. if (null != this.mQClientFactory.getClientConfig().getNamespace()) {
    7. msg.setInstanceId(this.mQClientFactory.getClientConfig().getNamespace());
    8. topicWithNamespace = true;
    9. }
    10. //消息大小超过4K,启用消息压缩
    11. int sysFlag = 0;
    12. boolean msgBodyCompressed = false;
    13. if (this.tryToCompressMessage(msg)) {
    14. sysFlag |= MessageSysFlag.COMPRESSED_FLAG;
    15. msgBodyCompressed = true;
    16. }
    17. //如果是事务消息,设置消息标记MessageSysFlag.TRANSACTION_PREPARED_TYPE
    18. final String tranMsg = msg.getProperty(MessageConst.PROPERTY_TRANSACTION_PREPARED);
    19. if (tranMsg != null && Boolean.parseBoolean(tranMsg)) {
    20. sysFlag |= MessageSysFlag.TRANSACTION_PREPARED_TYPE;
    21. }
    1. //如果注册了消息发送钩子函数,在执行消息发送前的增强逻辑
    2. if (this.hasSendMessageHook()) {
    3. context = new SendMessageContext();
    4. context.setProducer(this);
    5. context.setProducerGroup(this.defaultMQProducer.getProducerGroup());
    6. context.setCommunicationMode(communicationMode);
    7. context.setBornHost(this.defaultMQProducer.getClientIP());
    8. context.setBrokerAddr(brokerAddr);
    9. context.setMessage(msg);
    10. context.setMq(mq);
    11. context.setNamespace(this.defaultMQProducer.getNamespace());
    12. String isTrans = msg.getProperty(MessageConst.PROPERTY_TRANSACTION_PREPARED);
    13. if (isTrans != null && isTrans.equals("true")) {
    14. context.setMsgType(MessageType.Trans_Msg_Half);
    15. }
    16. if (msg.getProperty("__STARTDELIVERTIME") != null || msg.getProperty(MessageConst.PROPERTY_DELAY_TIME_LEVEL) != null) {
    17. context.setMsgType(MessageType.Delay_Msg);
    18. }
    19. this.executeSendMessageHookBefore(context);
    20. }

    代码:SendMessageHook

    1. public interface SendMessageHook {
    2. String hookName();
    3. void sendMessageBefore(final SendMessageContext context);
    4. void sendMessageAfter(final SendMessageContext context);
    5. }

    代码:DefaultMQProducerImpl#sendKernelImpl

    1. //构建消息发送请求包
    2. SendMessageRequestHeader requestHeader = new SendMessageRequestHeader();
    3. //生产者组
    4. requestHeader.setProducerGroup(this.defaultMQProducer.getProducerGroup());
    5. //主题
    6. requestHeader.setTopic(msg.getTopic());
    7. //默认创建主题Key
    8. requestHeader.setDefaultTopic(this.defaultMQProducer.getCreateTopicKey());
    9. //该主题在单个Broker默认队列树
    10. requestHeader.setDefaultTopicQueueNums(this.defaultMQProducer.getDefaultTopicQueueNums());
    11. //队列ID
    12. requestHeader.setQueueId(mq.getQueueId());
    13. //消息系统标记
    14. requestHeader.setSysFlag(sysFlag);
    15. //消息发送时间
    16. requestHeader.setBornTimestamp(System.currentTimeMillis());
    17. //消息标记
    18. requestHeader.setFlag(msg.getFlag());
    19. //消息扩展信息
    20. requestHeader.setProperties(MessageDecoder.messageProperties2String(msg.getProperties()));
    21. //消息重试次数
    22. requestHeader.setReconsumeTimes(0);
    23. requestHeader.setUnitMode(this.isUnitMode());
    24. //是否是批量消息等
    25. requestHeader.setBatch(msg instanceof MessageBatch);
    26. if (requestHeader.getTopic().startsWith(MixAll.RETRY_GROUP_TOPIC_PREFIX)) {
    27. String reconsumeTimes = MessageAccessor.getReconsumeTime(msg);
    28. if (reconsumeTimes != null) {
    29. requestHeader.setReconsumeTimes(Integer.valueOf(reconsumeTimes));
    30. MessageAccessor.clearProperty(msg, MessageConst.PROPERTY_RECONSUME_TIME);
    31. }
    32. String maxReconsumeTimes = MessageAccessor.getMaxReconsumeTimes(msg);
    33. if (maxReconsumeTimes != null) {
    34. requestHeader.setMaxReconsumeTimes(Integer.valueOf(maxReconsumeTimes));
    35. MessageAccessor.clearProperty(msg, MessageConst.PROPERTY_MAX_RECONSUME_TIMES);
    36. }
    37. }
    1. case ASYNC: //异步发送
    2. Message tmpMessage = msg;
    3. boolean messageCloned = false;
    4. if (msgBodyCompressed) {
    5. //If msg body was compressed, msgbody should be reset using prevBody.
    6. //Clone new message using commpressed message body and recover origin massage.
    7. //Fix bug:https://github.com/apache/rocketmq-externals/issues/66
    8. tmpMessage = MessageAccessor.cloneMessage(msg);
    9. messageCloned = true;
    10. msg.setBody(prevBody);
    11. }
    12. if (topicWithNamespace) {
    13. if (!messageCloned) {
    14. tmpMessage = MessageAccessor.cloneMessage(msg);
    15. messageCloned = true;
    16. }
    17. msg.setTopic(NamespaceUtil.withoutNamespace(msg.getTopic(),
    18. this.defaultMQProducer.getNamespace()));
    19. }
    20. long costTimeAsync = System.currentTimeMillis() - beginStartTime;
    21. if (timeout < costTimeAsync) {
    22. throw new RemotingTooMuchRequestException("sendKernelImpl call timeout");
    23. }
    24. sendResult = this.mQClientFactory.getMQClientAPIImpl().sendMessage(
    25. brokerAddr,
    26. mq.getBrokerName(),
    27. tmpMessage,
    28. requestHeader,
    29. timeout - costTimeAsync,
    30. communicationMode,
    31. sendCallback,
    32. topicPublishInfo,
    33. this.mQClientFactory,
    34. this.defaultMQProducer.getRetryTimesWhenSendAsyncFailed(),
    35. context,
    36. this);
    37. break;
    38. case ONEWAY:
    39. case SYNC: //同步发送
    40. long costTimeSync = System.currentTimeMillis() - beginStartTime;
    41. if (timeout < costTimeSync) {
    42. throw new RemotingTooMuchRequestException("sendKernelImpl call timeout");
    43. }
    44. sendResult = this.mQClientFactory.getMQClientAPIImpl().sendMessage(
    45. brokerAddr,
    46. mq.getBrokerName(),
    47. msg,
    48. requestHeader,
    49. timeout - costTimeSync,
    50. communicationMode,
    51. context,
    52. this);
    53. break;
    54. default:
    55. assert false;
    56. break;
    57. }
    1. //如果注册了钩子函数,则发送完毕后执行钩子函数
    2. if (this.hasSendMessageHook()) {
    3. context.setSendResult(sendResult);
    4. this.executeSendMessageHookAfter(context);
    5. }

    2.3.4 批量消息发送

    RocketMQ-03 - 图50
    批量消息发送是将同一个主题的多条消息一起打包发送到消息服务端,减少网络调用次数,提高网络传输效率。当然,并不是在同一批次中发送的消息数量越多越好,其判断依据是单条消息的长度,如果单条消息内容比较长,则打包多条消息发送会影响其他线程发送消息的响应时间,并且单批次消息总长度不能超过DefaultMQProducer#maxMessageSize。
    批量消息发送要解决的问题是如何将这些消息编码以便服务端能够正确解码出每条消息的消息内容。
    代码:DefaultMQProducer#send

    1. public SendResult send(Collection<Message> msgs)
    2. throws MQClientException, RemotingException, MQBrokerException, InterruptedException {
    3. //压缩消息集合成一条消息,然后发送出去
    4. return this.defaultMQProducerImpl.send(batch(msgs));
    5. }

    代码:DefaultMQProducer#batch

    1. private MessageBatch batch(Collection<Message> msgs) throws MQClientException {
    2. MessageBatch msgBatch;
    3. try {
    4. //将集合消息封装到MessageBatch
    5. msgBatch = MessageBatch.generateFromList(msgs);
    6. //遍历消息集合,检查消息合法性,设置消息ID,设置Topic
    7. for (Message message : msgBatch) {
    8. Validators.checkMessage(message, this);
    9. MessageClientIDSetter.setUniqID(message);
    10. message.setTopic(withNamespace(message.getTopic()));
    11. }
    12. //压缩消息,设置消息body
    13. msgBatch.setBody(msgBatch.encode());
    14. } catch (Exception e) {
    15. throw new MQClientException("Failed to initiate the MessageBatch", e);
    16. }
    17. //设置msgBatch的topic
    18. msgBatch.setTopic(withNamespace(msgBatch.getTopic()));
    19. return msgBatch;
    20. }

    2.4 消息存储

    2.4.1 消息存储核心类
    RocketMQ-03 - 图51

    1. private final MessageStoreConfig messageStoreConfig; //消息配置属性
    2. private final CommitLog commitLog; //CommitLog文件存储的实现类
    3. private final ConcurrentMap<String/* topic */, ConcurrentMap<Integer/* queueId */, ConsumeQueue>> consumeQueueTable; //消息队列存储缓存表,按照消息主题分组
    4. private final FlushConsumeQueueService flushConsumeQueueService; //消息队列文件刷盘线程
    5. private final CleanCommitLogService cleanCommitLogService; //清除CommitLog文件服务
    6. private final CleanConsumeQueueService cleanConsumeQueueService; //清除ConsumerQueue队列文件服务
    7. private final IndexService indexService; //索引实现类
    8. private final AllocateMappedFileService allocateMappedFileService; //MappedFile分配服务
    9. private final ReputMessageService reputMessageService;//CommitLog消息分发,根据CommitLog文件构建ConsumerQueue、IndexFile文件
    10. private final HAService haService; //存储HA机制
    11. private final ScheduleMessageService scheduleMessageService; //消息服务调度线程
    12. private final StoreStatsService storeStatsService; //消息存储服务
    13. private final TransientStorePool transientStorePool; //消息堆外内存缓存
    14. private final BrokerStatsManager brokerStatsManager; //Broker状态管理器
    15. private final MessageArrivingListener messageArrivingListener; //消息拉取长轮询模式消息达到监听器
    16. private final BrokerConfig brokerConfig; //Broker配置类
    17. private StoreCheckpoint storeCheckpoint; //文件刷盘监测点
    18. private final LinkedList<CommitLogDispatcher> dispatcherList; //CommitLog文件转发请求

    2.4.2 消息存储流程

    RocketMQ-03 - 图52
    消息存储入口:DefaultMessageStore#putMessage

    1. //判断Broker角色如果是从节点,则无需写入
    2. if (BrokerRole.SLAVE == this.messageStoreConfig.getBrokerRole()) {
    3. long value = this.printTimes.getAndIncrement();
    4. if ((value % 50000) == 0) {
    5. log.warn("message store is slave mode, so putMessage is forbidden ");
    6. }
    7. return new PutMessageResult(PutMessageStatus.SERVICE_NOT_AVAILABLE, null);
    8. }
    9. //判断当前写入状态如果是正在写入,则不能继续
    10. if (!this.runningFlags.isWriteable()) {
    11. long value = this.printTimes.getAndIncrement();
    12. return new PutMessageResult(PutMessageStatus.SERVICE_NOT_AVAILABLE, null);
    13. } else {
    14. this.printTimes.set(0);
    15. }
    16. //判断消息主题长度是否超过最大限制
    17. if (msg.getTopic().length() > Byte.MAX_VALUE) {
    18. log.warn("putMessage message topic length too long " + msg.getTopic().length());
    19. return new PutMessageResult(PutMessageStatus.MESSAGE_ILLEGAL, null);
    20. }
    21. //判断消息属性长度是否超过限制
    22. if (msg.getPropertiesString() != null && msg.getPropertiesString().length() > Short.MAX_VALUE) {
    23. log.warn("putMessage message properties length too long " + msg.getPropertiesString().length());
    24. return new PutMessageResult(PutMessageStatus.PROPERTIES_SIZE_EXCEEDED, null);
    25. }
    26. //判断系统PageCache缓存去是否占用
    27. if (this.isOSPageCacheBusy()) {
    28. return new PutMessageResult(PutMessageStatus.OS_PAGECACHE_BUSY, null);
    29. }
    30. //将消息写入CommitLog文件
    31. PutMessageResult result = this.commitLog.putMessage(msg);

    代码:CommitLog#putMessage

    1. //记录消息存储时间
    2. msg.setStoreTimestamp(beginLockTimestamp);
    3. //判断如果mappedFile如果为空或者已满,创建新的mappedFile文件
    4. if (null == mappedFile || mappedFile.isFull()) {
    5. mappedFile = this.mappedFileQueue.getLastMappedFile(0);
    6. }
    7. //如果创建失败,直接返回
    8. if (null == mappedFile) {
    9. log.error("create mapped file1 error, topic: " + msg.getTopic() + " clientAddr: " + msg.getBornHostString());
    10. beginTimeInLock = 0;
    11. return new PutMessageResult(PutMessageStatus.CREATE_MAPEDFILE_FAILED, null);
    12. }
    13. //写入消息到mappedFile中
    14. result = mappedFile.appendMessage(msg, this.appendMessageCallback);

    代码:MappedFile#appendMessagesInner

    1. //获得文件的写入指针
    2. int currentPos = this.wrotePosition.get();
    3. //如果指针大于文件大小则直接返回
    4. if (currentPos < this.fileSize) {
    5. //通过writeBuffer.slice()创建一个与MappedFile共享的内存区,并设置position为当前指针
    6. ByteBuffer byteBuffer = writeBuffer != null ? writeBuffer.slice() : this.mappedByteBuffer.slice();
    7. byteBuffer.position(currentPos);
    8. AppendMessageResult result = null;
    9. if (messageExt instanceof MessageExtBrokerInner) {
    10. //通过回调方法写入
    11. result = cb.doAppend(this.getFileFromOffset(), byteBuffer, this.fileSize - currentPos, (MessageExtBrokerInner) messageExt);
    12. } else if (messageExt instanceof MessageExtBatch) {
    13. result = cb.doAppend(this.getFileFromOffset(), byteBuffer, this.fileSize - currentPos, (MessageExtBatch) messageExt);
    14. } else {
    15. return new AppendMessageResult(AppendMessageStatus.UNKNOWN_ERROR);
    16. }
    17. this.wrotePosition.addAndGet(result.getWroteBytes());
    18. this.storeTimestamp = result.getStoreTimestamp();
    19. return result;
    20. }

    代码:CommitLog#doAppend

    1. //文件写入位置
    2. long wroteOffset = fileFromOffset + byteBuffer.position();
    3. //设置消息ID
    4. this.resetByteBuffer(hostHolder, 8);
    5. String msgId = MessageDecoder.createMessageId(this.msgIdMemory, msgInner.getStoreHostBytes(hostHolder), wroteOffset);
    6. //获得该消息在消息队列中的偏移量
    7. keyBuilder.setLength(0);
    8. keyBuilder.append(msgInner.getTopic());
    9. keyBuilder.append('-');
    10. keyBuilder.append(msgInner.getQueueId());
    11. String key = keyBuilder.toString();
    12. Long queueOffset = CommitLog.this.topicQueueTable.get(key);
    13. if (null == queueOffset) {
    14. queueOffset = 0L;
    15. CommitLog.this.topicQueueTable.put(key, queueOffset);
    16. }
    17. //获得消息属性长度
    18. final byte[] propertiesData =msgInner.getPropertiesString() == null ? null : msgInner.getPropertiesString().getBytes(MessageDecoder.CHARSET_UTF8);
    19. final int propertiesLength = propertiesData == null ? 0 : propertiesData.length;
    20. if (propertiesLength > Short.MAX_VALUE) {
    21. log.warn("putMessage message properties length too long. length={}", propertiesData.length);
    22. return new AppendMessageResult(AppendMessageStatus.PROPERTIES_SIZE_EXCEEDED);
    23. }
    24. //获得消息主题大小
    25. final byte[] topicData = msgInner.getTopic().getBytes(MessageDecoder.CHARSET_UTF8);
    26. final int topicLength = topicData.length;
    27. //获得消息体大小
    28. final int bodyLength = msgInner.getBody() == null ? 0 : msgInner.getBody().length;
    29. //计算消息总长度
    30. final int msgLen = calMsgLength(bodyLength, topicLength, propertiesLength);

    代码:CommitLog#calMsgLength

    1. protected static int calMsgLength(int bodyLength, int topicLength, int propertiesLength) {
    2. final int msgLen = 4 //TOTALSIZE
    3. + 4 //MAGICCODE
    4. + 4 //BODYCRC
    5. + 4 //QUEUEID
    6. + 4 //FLAG
    7. + 8 //QUEUEOFFSET
    8. + 8 //PHYSICALOFFSET
    9. + 4 //SYSFLAG
    10. + 8 //BORNTIMESTAMP
    11. + 8 //BORNHOST
    12. + 8 //STORETIMESTAMP
    13. + 8 //STOREHOSTADDRESS
    14. + 4 //RECONSUMETIMES
    15. + 8 //Prepared Transaction Offset
    16. + 4 + (bodyLength > 0 ? bodyLength : 0) //BODY
    17. + 1 + topicLength //TOPIC
    18. + 2 + (propertiesLength > 0 ? propertiesLength : 0) //propertiesLength
    19. + 0;
    20. return msgLen;
    21. }

    代码:CommitLog#doAppend

    1. //消息长度不能超过4M
    2. if (msgLen > this.maxMessageSize) {
    3. CommitLog.log.warn("message size exceeded, msg total size: " + msgLen + ", msg body size: " + bodyLength
    4. + ", maxMessageSize: " + this.maxMessageSize);
    5. return new AppendMessageResult(AppendMessageStatus.MESSAGE_SIZE_EXCEEDED);
    6. }
    7. //消息是如果没有足够的存储空间则新创建CommitLog文件
    8. if ((msgLen + END_FILE_MIN_BLANK_LENGTH) > maxBlank) {
    9. this.resetByteBuffer(this.msgStoreItemMemory, maxBlank);
    10. // 1 TOTALSIZE
    11. this.msgStoreItemMemory.putInt(maxBlank);
    12. // 2 MAGICCODE
    13. this.msgStoreItemMemory.putInt(CommitLog.BLANK_MAGIC_CODE);
    14. // 3 The remaining space may be any value
    15. // Here the length of the specially set maxBlank
    16. final long beginTimeMills = CommitLog.this.defaultMessageStore.now();
    17. byteBuffer.put(this.msgStoreItemMemory.array(), 0, maxBlank);
    18. return new AppendMessageResult(AppendMessageStatus.END_OF_FILE, wroteOffset, maxBlank, msgId, msgInner.getStoreTimestamp(),
    19. queueOffset, CommitLog.this.defaultMessageStore.now() - beginTimeMills);
    20. }
    21. //将消息存储到ByteBuffer中,返回AppendMessageResult
    22. final long beginTimeMills = CommitLog.this.defaultMessageStore.now();
    23. // Write messages to the queue buffer
    24. byteBuffer.put(this.msgStoreItemMemory.array(), 0, msgLen);
    25. AppendMessageResult result = new AppendMessageResult(AppendMessageStatus.PUT_OK, wroteOffset,
    26. msgLen, msgId,msgInner.getStoreTimestamp(),
    27. queueOffset,
    28. CommitLog.this.defaultMessageStore.now()
    29. -beginTimeMills);
    30. switch (tranType) {
    31. case MessageSysFlag.TRANSACTION_PREPARED_TYPE:
    32. case MessageSysFlag.TRANSACTION_ROLLBACK_TYPE:
    33. break;
    34. case MessageSysFlag.TRANSACTION_NOT_TYPE:
    35. case MessageSysFlag.TRANSACTION_COMMIT_TYPE:
    36. //更新消息队列偏移量
    37. CommitLog.this.topicQueueTable.put(key, ++queueOffset);
    38. break;
    39. default:
    40. break;
    41. }

    代码:CommitLog#putMessage

    1. //释放锁
    2. putMessageLock.unlock();
    3. //刷盘
    4. handleDiskFlush(result, putMessageResult, msg);
    5. //执行HA主从同步
    6. handleHA(result, putMessageResult, msg);

    2.4.3 存储文件

    RocketMQ-03 - 图53

  • commitLog:消息存储目录

  • config:运行期间一些配置信息
  • consumerqueue:消息消费队列存储目录
  • index:消息索引文件存储目录
  • abort:如果存在改文件寿命Broker非正常关闭
  • checkpoint:文件检查点,存储CommitLog文件最后一次刷盘时间戳、consumerquueue最后一次刷盘时间,index索引文件最后一次刷盘时间戳。

    2.4.4 存储文件内存映射

    RocketMQ通过使用内存映射文件提高IO访问性能,无论是CommitLog、ConsumerQueue还是IndexFile,单个文件都被设计为固定长度,如果一个文件写满以后再创建一个新文件,文件名就为该文件第一条消息对应的全局物理偏移量。
    ####1)MappedFileQueue
    RocketMQ-03 - 图54

    1. String storePath; //存储目录
    2. int mappedFileSize; // 单个文件大小
    3. CopyOnWriteArrayList<MappedFile> mappedFiles; //MappedFile文件集合
    4. AllocateMappedFileService allocateMappedFileService; //创建MapFile服务类
    5. long flushedWhere = 0; //当前刷盘指针
    6. long committedWhere = 0; //当前数据提交指针,内存中ByteBuffer当前的写指针,该值大于等于flushWhere
  • 根据存储时间查询MappedFile

    1. public MappedFile getMappedFileByTime(final long timestamp) {
    2. Object[] mfs = this.copyMappedFiles(0);
    3. if (null == mfs)
    4. return null;
    5. //遍历MappedFile文件数组
    6. for (int i = 0; i < mfs.length; i++) {
    7. MappedFile mappedFile = (MappedFile) mfs[i];
    8. //MappedFile文件的最后修改时间大于指定时间戳则返回该文件
    9. if (mappedFile.getLastModifiedTimestamp() >= timestamp) {
    10. return mappedFile;
    11. }
    12. }
    13. return (MappedFile) mfs[mfs.length - 1];
    14. }
  • 根据消息偏移量offset查找MappedFile

    1. public MappedFile findMappedFileByOffset(final long offset, final boolean returnFirstOnNotFound) {
    2. try {
    3. //获得第一个MappedFile文件
    4. MappedFile firstMappedFile = this.getFirstMappedFile();
    5. //获得最后一个MappedFile文件
    6. MappedFile lastMappedFile = this.getLastMappedFile();
    7. //第一个文件和最后一个文件均不为空,则进行处理
    8. if (firstMappedFile != null && lastMappedFile != null) {
    9. if (offset < firstMappedFile.getFileFromOffset() ||
    10. offset >= lastMappedFile.getFileFromOffset() + this.mappedFileSize) {
    11. } else {
    12. //获得文件索引
    13. int index = (int) ((offset / this.mappedFileSize)
    14. - (firstMappedFile.getFileFromOffset() / this.mappedFileSize));
    15. MappedFile targetFile = null;
    16. try {
    17. //根据索引返回目标文件
    18. targetFile = this.mappedFiles.get(index);
    19. } catch (Exception ignored) {
    20. }
    21. if (targetFile != null && offset >= targetFile.getFileFromOffset()
    22. && offset < targetFile.getFileFromOffset() + this.mappedFileSize) {
    23. return targetFile;
    24. }
    25. for (MappedFile tmpMappedFile : this.mappedFiles) {
    26. if (offset >= tmpMappedFile.getFileFromOffset()
    27. && offset < tmpMappedFile.getFileFromOffset() + this.mappedFileSize) {
    28. return tmpMappedFile;
    29. }
    30. }
    31. }
    32. if (returnFirstOnNotFound) {
    33. return firstMappedFile;
    34. }
    35. }
    36. } catch (Exception e) {
    37. log.error("findMappedFileByOffset Exception", e);
    38. }
    39. return null;
    40. }
  • 获取存储文件最小偏移量

    1. public long getMinOffset() {
    2. if (!this.mappedFiles.isEmpty()) {
    3. try {
    4. return this.mappedFiles.get(0).getFileFromOffset();
    5. } catch (IndexOutOfBoundsException e) {
    6. //continue;
    7. } catch (Exception e) {
    8. log.error("getMinOffset has exception.", e);
    9. }
    10. }
    11. return -1;
    12. }
  • 获取存储文件最大偏移量

    1. public long getMaxOffset() {
    2. MappedFile mappedFile = getLastMappedFile();
    3. if (mappedFile != null) {
    4. return mappedFile.getFileFromOffset() + mappedFile.getReadPosition();
    5. }
    6. return 0;
    7. }
  • 返回存储文件当前写指针

    1. public long getMaxWrotePosition() {
    2. MappedFile mappedFile = getLastMappedFile();
    3. if (mappedFile != null) {
    4. return mappedFile.getFileFromOffset() + mappedFile.getWrotePosition();
    5. }
    6. return 0;
    7. }

    2)MappedFile
    RocketMQ-03 - 图55

    1. int OS_PAGE_SIZE = 1024 * 4; //操作系统每页大小,默认4K
    2. AtomicLong TOTAL_MAPPED_VIRTUAL_MEMORY = new AtomicLong(0); //当前JVM实例中MappedFile虚拟内存
    3. AtomicInteger TOTAL_MAPPED_FILES = new AtomicInteger(0); //当前JVM实例中MappedFile对象个数
    4. AtomicInteger wrotePosition = new AtomicInteger(0); //当前文件的写指针
    5. AtomicInteger committedPosition = new AtomicInteger(0); //当前文件的提交指针
    6. AtomicInteger flushedPosition = new AtomicInteger(0); //刷写到磁盘指针
    7. int fileSize; //文件大小
    8. FileChannel fileChannel; //文件通道
    9. ByteBuffer writeBuffer = null; //堆外内存ByteBuffer
    10. TransientStorePool transientStorePool = null; //堆外内存池
    11. String fileName; //文件名称
    12. long fileFromOffset; //该文件的处理偏移量
    13. File file; //物理文件
    14. MappedByteBuffer mappedByteBuffer; //物理文件对应的内存映射Buffer
    15. volatile long storeTimestamp = 0; //文件最后一次内容写入时间
    16. boolean firstCreateInQueue = false; //是否是MappedFileQueue队列中第一个文件

    MappedFile初始化

  • 未开启transientStorePoolEnabletransientStorePoolEnable=truetrue表示数据先存储到堆外内存,然后通过Commit线程将数据提交到内存映射Buffer中,再通过Flush线程将内存映射Buffer中数据持久化磁盘。

    1. private void init(final String fileName, final int fileSize) throws IOException {
    2. this.fileName = fileName;
    3. this.fileSize = fileSize;
    4. this.file = new File(fileName);
    5. this.fileFromOffset = Long.parseLong(this.file.getName());
    6. boolean ok = false;
    7. ensureDirOK(this.file.getParent());
    8. try {
    9. this.fileChannel = new RandomAccessFile(this.file, "rw").getChannel();
    10. this.mappedByteBuffer = this.fileChannel.map(MapMode.READ_WRITE, 0, fileSize);
    11. TOTAL_MAPPED_VIRTUAL_MEMORY.addAndGet(fileSize);
    12. TOTAL_MAPPED_FILES.incrementAndGet();
    13. ok = true;
    14. } catch (FileNotFoundException e) {
    15. log.error("create file channel " + this.fileName + " Failed. ", e);
    16. throw e;
    17. } catch (IOException e) {
    18. log.error("map file " + this.fileName + " Failed. ", e);
    19. throw e;
    20. } finally {
    21. if (!ok && this.fileChannel != null) {
    22. this.fileChannel.close();
    23. }
    24. }
    25. }

    开启transientStorePoolEnable

    1. public void init(final String fileName, final int fileSize,
    2. final TransientStorePool transientStorePool) throws IOException {
    3. init(fileName, fileSize);
    4. this.writeBuffer = transientStorePool.borrowBuffer(); //初始化writeBuffer
    5. this.transientStorePool = transientStorePool;
    6. }

    MappedFile提交
    提交数据到FileChannel,commitLeastPages为本次提交最小的页数,如果待提交数据不满commitLeastPages,则不执行本次提交操作。如果writeBuffer如果为空,直接返回writePosition指针,无需执行commit操作,表名commit操作主体是writeBuffer。

    1. public int commit(final int commitLeastPages) {
    2. if (writeBuffer == null) {
    3. //no need to commit data to file channel, so just regard wrotePosition as committedPosition.
    4. return this.wrotePosition.get();
    5. }
    6. //判断是否满足提交条件
    7. if (this.isAbleToCommit(commitLeastPages)) {
    8. if (this.hold()) {
    9. commit0(commitLeastPages);
    10. this.release();
    11. } else {
    12. log.warn("in commit, hold failed, commit offset = " + this.committedPosition.get());
    13. }
    14. }
    15. // 所有数据提交后,清空缓冲区
    16. if (writeBuffer != null && this.transientStorePool != null && this.fileSize == this.committedPosition.get()) {
    17. this.transientStorePool.returnBuffer(writeBuffer);
    18. this.writeBuffer = null;
    19. }
    20. return this.committedPosition.get();
    21. }

    MappedFile#isAbleToCommit
    判断是否执行commit操作,如果文件已满返回true;如果commitLeastpages大于0,则比较writePosition与上一次提交的指针commitPosition的差值,除以OS_PAGE_SIZE得到当前脏页的数量,如果大于commitLeastPages则返回true,如果commitLeastpages小于0表示只要存在脏页就提交。

    1. protected boolean isAbleToCommit(final int commitLeastPages) {
    2. //已经刷盘指针
    3. int flush = this.committedPosition.get();
    4. //文件写指针
    5. int write = this.wrotePosition.get();
    6. //写满刷盘
    7. if (this.isFull()) {
    8. return true;
    9. }
    10. if (commitLeastPages > 0) {
    11. //文件内容达到commitLeastPages页数,则刷盘
    12. return ((write / OS_PAGE_SIZE) - (flush / OS_PAGE_SIZE)) >= commitLeastPages;
    13. }
    14. return write > flush;
    15. }

    MappedFile#commit0
    具体提交的实现,首先创建WriteBuffer区共享缓存区,然后将新创建的position回退到上一次提交的位置(commitPosition),设置limit为wrotePosition(当前最大有效数据指针),然后把commitPosition到wrotePosition的数据写入到FileChannel中,然后更新committedPosition指针为wrotePosition。commit的作用就是将MappedFile的writeBuffer中数据提交到文件通道FileChannel中。

    1. protected void commit0(final int commitLeastPages) {
    2. //写指针
    3. int writePos = this.wrotePosition.get();
    4. //上次提交指针
    5. int lastCommittedPosition = this.committedPosition.get();
    6. if (writePos - this.committedPosition.get() > 0) {
    7. try {
    8. //复制共享内存区域
    9. ByteBuffer byteBuffer = writeBuffer.slice();
    10. //设置提交位置是上次提交位置
    11. byteBuffer.position(lastCommittedPosition);
    12. //最大提交数量
    13. byteBuffer.limit(writePos);
    14. //设置fileChannel位置为上次提交位置
    15. this.fileChannel.position(lastCommittedPosition);
    16. //将lastCommittedPosition到writePos的数据复制到FileChannel中
    17. this.fileChannel.write(byteBuffer);
    18. //重置提交位置
    19. this.committedPosition.set(writePos);
    20. } catch (Throwable e) {
    21. log.error("Error occurred when commit data to FileChannel.", e);
    22. }
    23. }
    24. }

    MappedFile#flush
    刷写磁盘,直接调用MappedByteBuffer或fileChannel的force方法将内存中的数据持久化到磁盘,那么flushedPosition应该等于MappedByteBuffer中的写指针;如果writeBuffer不为空,则flushPosition应该等于上一次的commit指针;因为上一次提交的数据就是进入到MappedByteBuffer中的数据;如果writeBuffer为空,数据时直接进入到MappedByteBuffer,wrotePosition代表的是MappedByteBuffer中的指针,故设置flushPosition为wrotePosition。
    RocketMQ-03 - 图56

    1. public int flush(final int flushLeastPages) {
    2. //数据达到刷盘条件
    3. if (this.isAbleToFlush(flushLeastPages)) {
    4. //加锁,同步刷盘
    5. if (this.hold()) {
    6. //获得读指针
    7. int value = getReadPosition();
    8. try {
    9. //数据从writeBuffer提交数据到fileChannel再刷新到磁盘
    10. if (writeBuffer != null || this.fileChannel.position() != 0) {
    11. this.fileChannel.force(false);
    12. } else {
    13. //从mmap刷新数据到磁盘
    14. this.mappedByteBuffer.force();
    15. }
    16. } catch (Throwable e) {
    17. log.error("Error occurred when force data to disk.", e);
    18. }
    19. //更新刷盘位置
    20. this.flushedPosition.set(value);
    21. this.release();
    22. } else {
    23. log.warn("in flush, hold failed, flush offset = " + this.flushedPosition.get());
    24. this.flushedPosition.set(getReadPosition());
    25. }
    26. }
    27. return this.getFlushedPosition();
    28. }

    MappedFile#getReadPosition
    获取当前文件最大可读指针。如果writeBuffer为空,则直接返回当前的写指针;如果writeBuffer不为空,则返回上一次提交的指针。在MappedFile设置中,只有提交了的数据(写入到MappedByteBuffer或FileChannel中的数据)才是安全的数据

    1. public int getReadPosition() {
    2. //如果writeBuffer为空,刷盘的位置就是应该等于上次commit的位置,如果为空则为mmap的写指针
    3. return this.writeBuffer == null ? this.wrotePosition.get() : this.committedPosition.get();
    4. }

    MappedFile#selectMappedBuffer
    查找pos到当前最大可读之间的数据,由于在整个写入期间都未曾改MappedByteBuffer的指针,如果mappedByteBuffer.slice()方法返回的共享缓存区空间为整个MappedFile,然后通过设置ByteBuffer的position为待查找的值,读取字节长度当前可读最大长度,最终返回的ByteBuffer的limit为size。整个共享缓存区的容量为(MappedFile#fileSize-pos)。故在操作SelectMappedBufferResult不能对包含在里面的ByteBuffer调用filp方法。

    1. public SelectMappedBufferResult selectMappedBuffer(int pos) {
    2. //获得最大可读指针
    3. int readPosition = getReadPosition();
    4. //pos小于最大可读指针,并且大于0
    5. if (pos < readPosition && pos >= 0) {
    6. if (this.hold()) {
    7. //复制mappedByteBuffer读共享区
    8. ByteBuffer byteBuffer = this.mappedByteBuffer.slice();
    9. //设置读指针位置
    10. byteBuffer.position(pos);
    11. //获得可读范围
    12. int size = readPosition - pos;
    13. //设置最大刻度范围
    14. ByteBuffer byteBufferNew = byteBuffer.slice();
    15. byteBufferNew.limit(size);
    16. return new SelectMappedBufferResult(this.fileFromOffset + pos, byteBufferNew, size, this);
    17. }
    18. }
    19. return null;
    20. }

    MappedFile#shutdown
    MappedFile文件销毁的实现方法为public boolean destory(long intervalForcibly),intervalForcibly表示拒绝被销毁的最大存活时间。

    1. public void shutdown(final long intervalForcibly) {
    2. if (this.available) {
    3. //关闭MapedFile
    4. this.available = false;
    5. //设置当前关闭时间戳
    6. this.firstShutdownTimestamp = System.currentTimeMillis();
    7. //释放资源
    8. this.release();
    9. } else if (this.getRefCount() > 0) {
    10. if ((System.currentTimeMillis() - this.firstShutdownTimestamp) >= intervalForcibly) {
    11. this.refCount.set(-1000 - this.getRefCount());
    12. this.release();
    13. }
    14. }
    15. }

    3)TransientStorePool

    短暂的存储池。RocketMQ单独创建一个MappedByteBuffer内存缓存池,用来临时存储数据,数据先写入该内存映射中,然后由commit线程定时将数据从该内存复制到与目标物理文件对应的内存映射中。RocketMQ引入该机制主要的原因是提供一种内存锁定,将当前堆外内存一直锁定在内存中,避免被进程将内存交换到磁盘。
    RocketMQ-03 - 图57

    1. private final int poolSize; //availableBuffers个数
    2. private final int fileSize; //每隔ByteBuffer大小
    3. private final Deque<ByteBuffer> availableBuffers; //ByteBuffer容器。双端队列

    初始化

    1. public void init() {
    2. //创建poolSize个堆外内存
    3. for (int i = 0; i < poolSize; i++) {
    4. ByteBuffer byteBuffer = ByteBuffer.allocateDirect(fileSize);
    5. final long address = ((DirectBuffer) byteBuffer).address();
    6. Pointer pointer = new Pointer(address);
    7. //使用com.sun.jna.Library类库将该批内存锁定,避免被置换到交换区,提高存储性能
    8. LibC.INSTANCE.mlock(pointer, new NativeLong(fileSize));
    9. availableBuffers.offer(byteBuffer);
    10. }
    11. }

    2.4.5 实时更新消息消费队列与索引文件

    消息消费队文件、消息属性索引文件都是基于CommitLog文件构建的,当消息生产者提交的消息存储在CommitLog文件中,ConsumerQueue、IndexFile需要及时更新,否则消息无法及时被消费,根据消息属性查找消息也会出现较大延迟。RocketMQ通过开启一个线程ReputMessageService来准实时转发CommitLog文件更新事件,相应的任务处理器根据转发的消息及时更新ConsumerQueue、IndexFile文件。
    RocketMQ-03 - 图58
    RocketMQ-03 - 图59
    代码:DefaultMessageStore:start

    1. //设置CommitLog内存中最大偏移量
    2. this.reputMessageService.setReputFromOffset(maxPhysicalPosInLogicQueue);
    3. //启动
    4. this.reputMessageService.start();

    代码:DefaultMessageStore:run

    1. public void run() {
    2. DefaultMessageStore.log.info(this.getServiceName() + " service started");
    3. //每隔1毫秒就继续尝试推送消息到消息消费队列和索引文件
    4. while (!this.isStopped()) {
    5. try {
    6. Thread.sleep(1);
    7. this.doReput();
    8. } catch (Exception e) {
    9. DefaultMessageStore.log.warn(this.getServiceName() + " service has exception. ", e);
    10. }
    11. }
    12. DefaultMessageStore.log.info(this.getServiceName() + " service end");
    13. }

    代码:DefaultMessageStore:deReput

    1. //从result中循环遍历消息,一次读一条,创建DispatherRequest对象。
    2. for (int readSize = 0; readSize < result.getSize() && doNext; ) {
    3. DispatchRequest dispatchRequest = DefaultMessageStore.this.commitLog.checkMessageAndReturnSize(result.getByteBuffer(), false, false);
    4. int size = dispatchRequest.getBufferSize() == -1 ? dispatchRequest.getMsgSize() : dispatchRequest.getBufferSize();
    5. if (dispatchRequest.isSuccess()) {
    6. if (size > 0) {
    7. DefaultMessageStore.this.doDispatch(dispatchRequest);
    8. }
    9. }
    10. }

    DispatchRequest
    RocketMQ-03 - 图60

    1. String topic; //消息主题名称
    2. int queueId; //消息队列ID
    3. long commitLogOffset; //消息物理偏移量
    4. int msgSize; //消息长度
    5. long tagsCode; //消息过滤tag hashCode
    6. long storeTimestamp; //消息存储时间戳
    7. long consumeQueueOffset; //消息队列偏移量
    8. String keys; //消息索引key
    9. boolean success; //是否成功解析到完整的消息
    10. String uniqKey; //消息唯一键
    11. int sysFlag; //消息系统标记
    12. long preparedTransactionOffset; //消息预处理事务偏移量
    13. Map<String, String> propertiesMap; //消息属性
    14. byte[] bitMap; //位图

    1)转发到ConsumerQueue

    RocketMQ-03 - 图61

    1. class CommitLogDispatcherBuildConsumeQueue implements CommitLogDispatcher {
    2. @Override
    3. public void dispatch(DispatchRequest request) {
    4. final int tranType = MessageSysFlag.getTransactionValue(request.getSysFlag());
    5. switch (tranType) {
    6. case MessageSysFlag.TRANSACTION_NOT_TYPE:
    7. case MessageSysFlag.TRANSACTION_COMMIT_TYPE:
    8. //消息分发
    9. DefaultMessageStore.this.putMessagePositionInfo(request);
    10. break;
    11. case MessageSysFlag.TRANSACTION_PREPARED_TYPE:
    12. case MessageSysFlag.TRANSACTION_ROLLBACK_TYPE:
    13. break;
    14. }
    15. }
    16. }

    代码:DefaultMessageStore#putMessagePositionInfo

    1. public void putMessagePositionInfo(DispatchRequest dispatchRequest) {
    2. //获得消费队列
    3. ConsumeQueue cq = this.findConsumeQueue(dispatchRequest.getTopic(), dispatchRequest.getQueueId());
    4. //消费队列分发消息
    5. cq.putMessagePositionInfoWrapper(dispatchRequest);
    6. }

    代码:DefaultMessageStore#putMessagePositionInfo

    1. //依次将消息偏移量、消息长度、tag写入到ByteBuffer中
    2. this.byteBufferIndex.flip();
    3. this.byteBufferIndex.limit(CQ_STORE_UNIT_SIZE);
    4. this.byteBufferIndex.putLong(offset);
    5. this.byteBufferIndex.putInt(size);
    6. this.byteBufferIndex.putLong(tagsCode);
    7. //获得内存映射文件
    8. MappedFile mappedFile = this.mappedFileQueue.getLastMappedFile(expectLogicOffset);
    9. if (mappedFile != null) {
    10. //将消息追加到内存映射文件,异步输盘
    11. return mappedFile.appendMessage(this.byteBufferIndex.array());
    12. }

    2)转发到Index

    RocketMQ-03 - 图62

    1. class CommitLogDispatcherBuildIndex implements CommitLogDispatcher {
    2. @Override
    3. public void dispatch(DispatchRequest request) {
    4. if (DefaultMessageStore.this.messageStoreConfig.isMessageIndexEnable()) {
    5. DefaultMessageStore.this.indexService.buildIndex(request);
    6. }
    7. }
    8. }

    代码:DefaultMessageStore#buildIndex

    1. public void buildIndex(DispatchRequest req) {
    2. //获得索引文件
    3. IndexFile indexFile = retryGetAndCreateIndexFile();
    4. if (indexFile != null) {
    5. //获得文件最大物理偏移量
    6. long endPhyOffset = indexFile.getEndPhyOffset();
    7. DispatchRequest msg = req;
    8. String topic = msg.getTopic();
    9. String keys = msg.getKeys();
    10. //如果该消息的物理偏移量小于索引文件中的最大物理偏移量,则说明是重复数据,忽略本次索引构建
    11. if (msg.getCommitLogOffset() < endPhyOffset) {
    12. return;
    13. }
    14. final int tranType = MessageSysFlag.getTransactionValue(msg.getSysFlag());
    15. switch (tranType) {
    16. case MessageSysFlag.TRANSACTION_NOT_TYPE:
    17. case MessageSysFlag.TRANSACTION_PREPARED_TYPE:
    18. case MessageSysFlag.TRANSACTION_COMMIT_TYPE:
    19. break;
    20. case MessageSysFlag.TRANSACTION_ROLLBACK_TYPE:
    21. return;
    22. }
    23. //如果消息ID不为空,则添加到Hash索引中
    24. if (req.getUniqKey() != null) {
    25. indexFile = putKey(indexFile, msg, buildKey(topic, req.getUniqKey()));
    26. if (indexFile == null) {
    27. return;
    28. }
    29. }
    30. //构建索引key,RocketMQ支持为同一个消息建立多个索引,多个索引键空格隔开.
    31. if (keys != null && keys.length() > 0) {
    32. String[] keyset = keys.split(MessageConst.KEY_SEPARATOR);
    33. for (int i = 0; i < keyset.length; i++) {
    34. String key = keyset[i];
    35. if (key.length() > 0) {
    36. indexFile = putKey(indexFile, msg, buildKey(topic, key));
    37. if (indexFile == null) {
    38. return;
    39. }
    40. }
    41. }
    42. }
    43. } else {
    44. log.error("build index error, stop building index");
    45. }
    46. }

    2.4.6 消息队列和索引文件恢复

    由于RocketMQ存储首先将消息全量存储在CommitLog文件中,然后异步生成转发任务更新ConsumerQueue和Index文件。如果消息成功存储到CommitLog文件中,转发任务未成功执行,此时消息服务器Broker由于某个愿意宕机,导致CommitLog、ConsumerQueue、IndexFile文件数据不一致。如果不加以人工修复的话,会有一部分消息即便在CommitLog中文件中存在,但由于没有转发到ConsumerQueue,这部分消息将永远复发被消费者消费。
    RocketMQ-03 - 图63
    ####1)存储文件加载
    代码:DefaultMessageStore#load
    判断上一次是否异常退出。实现机制是Broker在启动时创建abort文件,在退出时通过JVM钩子函数删除abort文件。如果下次启动时存在abort文件。说明Broker时异常退出的,CommitLog与ConsumerQueue数据有可能不一致,需要进行修复。

    1. //判断临时文件是否存在
    2. boolean lastExitOK = !this.isTempFileExist();
    3. //根据临时文件判断当前Broker是否异常退出
    4. private boolean isTempFileExist() {
    5. String fileName = StorePathConfigHelper
    6. .getAbortFile(this.messageStoreConfig.getStorePathRootDir());
    7. File file = new File(fileName);
    8. return file.exists();
    9. }

    代码:DefaultMessageStore#load

    1. //加载延时队列
    2. if (null != scheduleMessageService) {
    3. result = result && this.scheduleMessageService.load();
    4. }
    5. // 加载CommitLog文件
    6. result = result && this.commitLog.load();
    7. // 加载消费队列文件
    8. result = result && this.loadConsumeQueue();
    9. if (result) {
    10. //加载存储监测点,监测点主要记录CommitLog文件、ConsumerQueue文件、Index索引文件的刷盘点
    11. this.storeCheckpoint =new StoreCheckpoint(StorePathConfigHelper.getStoreCheckpoint(this.messageStoreConfig.getStorePathRootDir()));
    12. //加载index文件
    13. this.indexService.load(lastExitOK);
    14. //根据Broker是否异常退出,执行不同的恢复策略
    15. this.recover(lastExitOK);
    16. }

    代码:MappedFileQueue#load
    加载CommitLog到映射文件

    1. //指向CommitLog文件目录
    2. File dir = new File(this.storePath);
    3. //获得文件数组
    4. File[] files = dir.listFiles();
    5. if (files != null) {
    6. // 文件排序
    7. Arrays.sort(files);
    8. //遍历文件
    9. for (File file : files) {
    10. //如果文件大小和配置文件不一致,退出
    11. if (file.length() != this.mappedFileSize) {
    12. return false;
    13. }
    14. try {
    15. //创建映射文件
    16. MappedFile mappedFile = new MappedFile(file.getPath(), mappedFileSize);
    17. mappedFile.setWrotePosition(this.mappedFileSize);
    18. mappedFile.setFlushedPosition(this.mappedFileSize);
    19. mappedFile.setCommittedPosition(this.mappedFileSize);
    20. //将映射文件添加到队列
    21. this.mappedFiles.add(mappedFile);
    22. log.info("load " + file.getPath() + " OK");
    23. } catch (IOException e) {
    24. log.error("load file " + file + " error", e);
    25. return false;
    26. }
    27. }
    28. }
    29. return true;

    代码:DefaultMessageStore#loadConsumeQueue
    加载消息消费队列

    1. //执行消费队列目录
    2. File dirLogic = new File(StorePathConfigHelper.getStorePathConsumeQueue(this.messageStoreConfig.getStorePathRootDir()));
    3. //遍历消费队列目录
    4. File[] fileTopicList = dirLogic.listFiles();
    5. if (fileTopicList != null) {
    6. for (File fileTopic : fileTopicList) {
    7. //获得子目录名称,即topic名称
    8. String topic = fileTopic.getName();
    9. //遍历子目录下的消费队列文件
    10. File[] fileQueueIdList = fileTopic.listFiles();
    11. if (fileQueueIdList != null) {
    12. //遍历文件
    13. for (File fileQueueId : fileQueueIdList) {
    14. //文件名称即队列ID
    15. int queueId;
    16. try {
    17. queueId = Integer.parseInt(fileQueueId.getName());
    18. } catch (NumberFormatException e) {
    19. continue;
    20. }
    21. //创建消费队列并加载到内存
    22. ConsumeQueue logic = new ConsumeQueue(
    23. topic,
    24. queueId,
    25. StorePathConfigHelper.getStorePathConsumeQueue(this.messageStoreConfig.getStorePathRootDir()),
    26. this.getMessageStoreConfig().getMapedFileSizeConsumeQueue(),
    27. this);
    28. this.putConsumeQueue(topic, queueId, logic);
    29. if (!logic.load()) {
    30. return false;
    31. }
    32. }
    33. }
    34. }
    35. }
    36. log.info("load logics queue all over, OK");
    37. return true;

    代码:IndexService#load
    加载索引文件

    1. public boolean load(final boolean lastExitOK) {
    2. //索引文件目录
    3. File dir = new File(this.storePath);
    4. //遍历索引文件
    5. File[] files = dir.listFiles();
    6. if (files != null) {
    7. //文件排序
    8. Arrays.sort(files);
    9. //遍历文件
    10. for (File file : files) {
    11. try {
    12. //加载索引文件
    13. IndexFile f = new IndexFile(file.getPath(), this.hashSlotNum, this.indexNum, 0, 0);
    14. f.load();
    15. if (!lastExitOK) {
    16. //索引文件上次的刷盘时间小于该索引文件的消息时间戳,该文件将立即删除
    17. if (f.getEndTimestamp() > this.defaultMessageStore.getStoreCheckpoint()
    18. .getIndexMsgTimestamp()) {
    19. f.destroy(0);
    20. continue;
    21. }
    22. }
    23. //将索引文件添加到队列
    24. log.info("load index file OK, " + f.getFileName());
    25. this.indexFileList.add(f);
    26. } catch (IOException e) {
    27. log.error("load file {} error", file, e);
    28. return false;
    29. } catch (NumberFormatException e) {
    30. log.error("load file {} error", file, e);
    31. }
    32. }
    33. }
    34. return true;
    35. }

    代码:DefaultMessageStore#recover
    文件恢复,根据Broker是否正常退出执行不同的恢复策略

    1. private void recover(final boolean lastExitOK) {
    2. //获得最大的物理便宜消费队列
    3. long maxPhyOffsetOfConsumeQueue = this.recoverConsumeQueue();
    4. if (lastExitOK) {
    5. //正常恢复
    6. this.commitLog.recoverNormally(maxPhyOffsetOfConsumeQueue);
    7. } else {
    8. //异常恢复
    9. this.commitLog.recoverAbnormally(maxPhyOffsetOfConsumeQueue);
    10. }
    11. //在CommitLog中保存每个消息消费队列当前的存储逻辑偏移量
    12. this.recoverTopicQueueTable();
    13. }

    代码:DefaultMessageStore#recoverTopicQueueTable
    恢复ConsumerQueue后,将在CommitLog实例中保存每隔消息队列当前的存储逻辑偏移量,这也是消息中不仅存储主题、消息队列ID、还存储了消息队列的关键所在。

    1. public void recoverTopicQueueTable() {
    2. HashMap<String/* topic-queueid */, Long/* offset */> table = new HashMap<String, Long>(1024);
    3. //CommitLog最小偏移量
    4. long minPhyOffset = this.commitLog.getMinOffset();
    5. //遍历消费队列,将消费队列保存在CommitLog中
    6. for (ConcurrentMap<Integer, ConsumeQueue> maps : this.consumeQueueTable.values()) {
    7. for (ConsumeQueue logic : maps.values()) {
    8. String key = logic.getTopic() + "-" + logic.getQueueId();
    9. table.put(key, logic.getMaxOffsetInQueue());
    10. logic.correctMinOffset(minPhyOffset);
    11. }
    12. }
    13. this.commitLog.setTopicQueueTable(table);
    14. }

    2)正常恢复
    代码:CommitLog#recoverNormally

    1. public void recoverNormally(long maxPhyOffsetOfConsumeQueue) {
    2. final List<MappedFile> mappedFiles = this.mappedFileQueue.getMappedFiles();
    3. if (!mappedFiles.isEmpty()) {
    4. //Broker正常停止再重启时,从倒数第三个开始恢复,如果不足3个文件,则从第一个文件开始恢复。
    5. int index = mappedFiles.size() - 3;
    6. if (index < 0)
    7. index = 0;
    8. MappedFile mappedFile = mappedFiles.get(index);
    9. ByteBuffer byteBuffer = mappedFile.sliceByteBuffer();
    10. long processOffset = mappedFile.getFileFromOffset();
    11. //代表当前已校验通过的offset
    12. long mappedFileOffset = 0;
    13. while (true) {
    14. //查找消息
    15. DispatchRequest dispatchRequest = this.checkMessageAndReturnSize(byteBuffer, checkCRCOnRecover);
    16. //消息长度
    17. int size = dispatchRequest.getMsgSize();
    18. //查找结果为true,并且消息长度大于0,表示消息正确.mappedFileOffset向前移动本消息长度
    19. if (dispatchRequest.isSuccess() && size > 0) {
    20. mappedFileOffset += size;
    21. }
    22. //如果查找结果为true且消息长度等于0,表示已到该文件末尾,如果还有下一个文件,则重置processOffset和MappedFileOffset重复查找下一个文件,否则跳出循环。
    23. else if (dispatchRequest.isSuccess() && size == 0) {
    24. index++;
    25. if (index >= mappedFiles.size()) {
    26. // Current branch can not happen
    27. break;
    28. } else {
    29. //取出每个文件
    30. mappedFile = mappedFiles.get(index);
    31. byteBuffer = mappedFile.sliceByteBuffer();
    32. processOffset = mappedFile.getFileFromOffset();
    33. mappedFileOffset = 0;
    34. }
    35. }
    36. // 查找结果为false,表明该文件未填满所有消息,跳出循环,结束循环
    37. else if (!dispatchRequest.isSuccess()) {
    38. log.info("recover physics file end, " + mappedFile.getFileName());
    39. break;
    40. }
    41. }
    42. //更新MappedFileQueue的flushedWhere和committedWhere指针
    43. processOffset += mappedFileOffset;
    44. this.mappedFileQueue.setFlushedWhere(processOffset);
    45. this.mappedFileQueue.setCommittedWhere(processOffset);
    46. //删除offset之后的所有文件
    47. this.mappedFileQueue.truncateDirtyFiles(processOffset);
    48. if (maxPhyOffsetOfConsumeQueue >= processOffset) {
    49. this.defaultMessageStore.truncateDirtyLogicFiles(processOffset);
    50. }
    51. } else {
    52. this.mappedFileQueue.setFlushedWhere(0);
    53. this.mappedFileQueue.setCommittedWhere(0);
    54. this.defaultMessageStore.destroyLogics();
    55. }
    56. }

    代码:MappedFileQueue#truncateDirtyFiles

    1. public void truncateDirtyFiles(long offset) {
    2. List<MappedFile> willRemoveFiles = new ArrayList<MappedFile>();
    3. //遍历目录下文件
    4. for (MappedFile file : this.mappedFiles) {
    5. //文件尾部的偏移量
    6. long fileTailOffset = file.getFileFromOffset() + this.mappedFileSize;
    7. //文件尾部的偏移量大于offset
    8. if (fileTailOffset > offset) {
    9. //offset大于文件的起始偏移量
    10. if (offset >= file.getFileFromOffset()) {
    11. //更新wrotePosition、committedPosition、flushedPosistion
    12. file.setWrotePosition((int) (offset % this.mappedFileSize));
    13. file.setCommittedPosition((int) (offset % this.mappedFileSize));
    14. file.setFlushedPosition((int) (offset % this.mappedFileSize));
    15. } else {
    16. //offset小于文件的起始偏移量,说明该文件是有效文件后面创建的,释放mappedFile占用内存,删除文件
    17. file.destroy(1000);
    18. willRemoveFiles.add(file);
    19. }
    20. }
    21. }
    22. this.deleteExpiredFile(willRemoveFiles);
    23. }

    3)异常恢复
    Broker异常停止文件恢复的实现为CommitLog#recoverAbnormally。异常文件恢复步骤与正常停止文件恢复流程基本相同,其主要差别有两个。首先,正常停止默认从倒数第三个文件开始进行恢复,而异常停止则需要从最后一个文件往前走,找到第一个消息存储正常的文件。其次,如果CommitLog目录没有消息文件,如果消息消费队列目录下存在文件,则需要销毁。
    代码:CommitLog#recoverAbnormally

    ```java if (!mappedFiles.isEmpty()) { // Looking beginning to recover from which file int index = mappedFiles.size() - 1; MappedFile mappedFile = null; for (; index >= 0; index—) {

    1. mappedFile = mappedFiles.get(index);
    2. //判断消息文件是否是一个正确的文件
    3. if (this.isMappedFileMatchedRecover(mappedFile)) {
    4. log.info("recover from this mapped file " + mappedFile.getFileName());
    5. break;
    6. }

    } //根据索引取出mappedFile文件 if (index < 0) {

    1. index = 0;
    2. mappedFile = mappedFiles.get(index);

    } //…验证消息的合法性,并将消息转发到消息消费队列和索引文件

}else{ //未找到mappedFile,重置flushWhere、committedWhere都为0,销毁消息队列文件 this.mappedFileQueue.setFlushedWhere(0); this.mappedFileQueue.setCommittedWhere(0); this.defaultMessageStore.destroyLogics(); }

  1. <a name="RpSy6"></a>
  2. ### 2.4.7 刷盘机制
  3. RocketMQ的存储是基于JDK NIO的内存映射机制(MappedByteBuffer)的,消息存储首先将消息追加到内存,再根据配置的刷盘策略在不同时间进行刷写磁盘。
  4. <a name="efoc1"></a>
  5. #### 同步刷盘
  6. 消息追加到内存后,立即将数据刷写到磁盘文件<br />![](img/%E5%90%8C%E6%AD%A5%E5%88%B7%E7%9B%98%E6%B5%81%E7%A8%8B.png#crop=0&crop=0&crop=1&crop=1&id=OrX6K&originalType=binary&ratio=1&rotation=0&showTitle=false&status=done&style=none&title=)<br />**_代码:CommitLog#handleDiskFlush_**
  7. ```java
  8. //刷盘服务
  9. final GroupCommitService service = (GroupCommitService) this.flushCommitLogService;
  10. if (messageExt.isWaitStoreMsgOK()) {
  11. //封装刷盘请求
  12. GroupCommitRequest request = new GroupCommitRequest(result.getWroteOffset() + result.getWroteBytes());
  13. //提交刷盘请求
  14. service.putRequest(request);
  15. //线程阻塞5秒,等待刷盘结束
  16. boolean flushOK = request.waitForFlush(this.defaultMessageStore.getMessageStoreConfig().getSyncFlushTimeout());
  17. if (!flushOK) {
  18. putMessageResult.setPutMessageStatus(PutMessageStatus.FLUSH_DISK_TIMEOUT);
  19. }

GroupCommitRequest
RocketMQ-03 - 图64

  1. long nextOffset; //刷盘点偏移量
  2. CountDownLatch countDownLatch = new CountDownLatch(1); //倒计树锁存器
  3. volatile boolean flushOK = false; //刷盘结果;默认为false

代码:GroupCommitService#run

  1. public void run() {
  2. CommitLog.log.info(this.getServiceName() + " service started");
  3. while (!this.isStopped()) {
  4. try {
  5. //线程等待10ms
  6. this.waitForRunning(10);
  7. //执行提交
  8. this.doCommit();
  9. } catch (Exception e) {
  10. CommitLog.log.warn(this.getServiceName() + " service has exception. ", e);
  11. }
  12. }
  13. ...
  14. }

代码:GroupCommitService#doCommit

  1. private void doCommit() {
  2. //加锁
  3. synchronized (this.requestsRead) {
  4. if (!this.requestsRead.isEmpty()) {
  5. //遍历requestsRead
  6. for (GroupCommitRequest req : this.requestsRead) {
  7. // There may be a message in the next file, so a maximum of
  8. // two times the flush
  9. boolean flushOK = false;
  10. for (int i = 0; i < 2 && !flushOK; i++) {
  11. flushOK = CommitLog.this.mappedFileQueue.getFlushedWhere() >= req.getNextOffset();
  12. //刷盘
  13. if (!flushOK) {
  14. CommitLog.this.mappedFileQueue.flush(0);
  15. }
  16. }
  17. //唤醒发送消息客户端
  18. req.wakeupCustomer(flushOK);
  19. }
  20. //更新刷盘监测点
  21. long storeTimestamp = CommitLog.this.mappedFileQueue.getStoreTimestamp();
  22. if (storeTimestamp > 0) { CommitLog.this.defaultMessageStore.getStoreCheckpoint().setPhysicMsgTimestamp(storeTimestamp);
  23. }
  24. this.requestsRead.clear();
  25. } else {
  26. // Because of individual messages is set to not sync flush, it
  27. // will come to this process
  28. CommitLog.this.mappedFileQueue.flush(0);
  29. }
  30. }
  31. }

异步刷盘

在消息追加到内存后,立即返回给消息发送端。如果开启transientStorePoolEnable,RocketMQ会单独申请一个与目标物理文件(commitLog)同样大小的堆外内存,该堆外内存将使用内存锁定,确保不会被置换到虚拟内存中去,消息首先追加到堆外内存,然后提交到物理文件的内存映射中,然后刷写到磁盘。如果未开启transientStorePoolEnable,消息直接追加到物理文件直接映射文件中,然后刷写到磁盘中。
RocketMQ-03 - 图65
开启transientStorePoolEnable后异步刷盘步骤:

  1. 将消息直接追加到ByteBuffer(堆外内存)
  2. CommitRealTimeService线程每隔200ms将ByteBuffer新追加内容提交到MappedByteBuffer中
  3. MappedByteBuffer在内存中追加提交的内容,wrotePosition指针向后移动
  4. commit操作成功返回,将committedPosition位置恢复
  5. FlushRealTimeService线程默认每500ms将MappedByteBuffer中新追加的内存刷写到磁盘

代码:CommitLog$CommitRealTimeService#run
提交线程工作机制

  1. //间隔时间,默认200ms
  2. int interval = CommitLog.this.defaultMessageStore.getMessageStoreConfig().getCommitIntervalCommitLog();
  3. //一次提交的至少页数
  4. int commitDataLeastPages = CommitLog.this.defaultMessageStore.getMessageStoreConfig().getCommitCommitLogLeastPages();
  5. //两次真实提交的最大间隔,默认200ms
  6. int commitDataThoroughInterval =
  7. CommitLog.this.defaultMessageStore.getMessageStoreConfig().getCommitCommitLogThoroughInterval();
  8. //上次提交间隔超过commitDataThoroughInterval,则忽略提交commitDataThoroughInterval参数,直接提交
  9. long begin = System.currentTimeMillis();
  10. if (begin >= (this.lastCommitTimestamp + commitDataThoroughInterval)) {
  11. this.lastCommitTimestamp = begin;
  12. commitDataLeastPages = 0;
  13. }
  14. //执行提交操作,将待提交数据提交到物理文件的内存映射区
  15. boolean result = CommitLog.this.mappedFileQueue.commit(commitDataLeastPages);
  16. long end = System.currentTimeMillis();
  17. if (!result) {
  18. this.lastCommitTimestamp = end; // result = false means some data committed.
  19. //now wake up flush thread.
  20. //唤醒刷盘线程
  21. flushCommitLogService.wakeup();
  22. }
  23. if (end - begin > 500) {
  24. log.info("Commit data to file costs {} ms", end - begin);
  25. }
  26. this.waitForRunning(interval);

代码:CommitLog$FlushRealTimeService#run
刷盘线程工作机制

  1. //表示await方法等待,默认false
  2. boolean flushCommitLogTimed = CommitLog.this.defaultMessageStore.getMessageStoreConfig().isFlushCommitLogTimed();
  3. //线程执行时间间隔
  4. int interval = CommitLog.this.defaultMessageStore.getMessageStoreConfig().getFlushIntervalCommitLog();
  5. //一次刷写任务至少包含页数
  6. int flushPhysicQueueLeastPages = CommitLog.this.defaultMessageStore.getMessageStoreConfig().getFlushCommitLogLeastPages();
  7. //两次真实刷写任务最大间隔
  8. int flushPhysicQueueThoroughInterval =
  9. CommitLog.this.defaultMessageStore.getMessageStoreConfig().getFlushCommitLogThoroughInterval();
  10. ...
  11. //距离上次提交间隔超过flushPhysicQueueThoroughInterval,则本次刷盘任务将忽略flushPhysicQueueLeastPages,直接提交
  12. long currentTimeMillis = System.currentTimeMillis();
  13. if (currentTimeMillis >= (this.lastFlushTimestamp + flushPhysicQueueThoroughInterval)) {
  14. this.lastFlushTimestamp = currentTimeMillis;
  15. flushPhysicQueueLeastPages = 0;
  16. printFlushProgress = (printTimes++ % 10) == 0;
  17. }
  18. ...
  19. //执行一次刷盘前,先等待指定时间间隔
  20. if (flushCommitLogTimed) {
  21. Thread.sleep(interval);
  22. } else {
  23. this.waitForRunning(interval);
  24. }
  25. ...
  26. long begin = System.currentTimeMillis();
  27. //刷写磁盘
  28. CommitLog.this.mappedFileQueue.flush(flushPhysicQueueLeastPages);
  29. long storeTimestamp = CommitLog.this.mappedFileQueue.getStoreTimestamp();
  30. if (storeTimestamp > 0) {
  31. //更新存储监测点文件的时间戳
  32. CommitLog.this.defaultMessageStore.getStoreCheckpoint().setPhysicMsgTimestamp(storeTimestamp);

2.4.8 过期文件删除机制

由于RocketMQ操作CommitLog、ConsumerQueue文件是基于内存映射机制并在启动的时候回加载CommitLog、ConsumerQueue目录下的所有文件,为了避免内存与磁盘的浪费,不可能将消息永久存储在消息服务器上,所以要引入一种机制来删除已过期的文件。RocketMQ顺序写CommitLog、ConsumerQueue文件,所有写操作全部落在最后一个CommitLog或者ConsumerQueue文件上,之前的文件在下一个文件创建后将不会再被更新。RocketMQ清除过期文件的方法时:如果当前文件在在一定时间间隔内没有再次被消费,则认为是过期文件,可以被删除,RocketMQ不会关注这个文件上的消息是否全部被消费。默认每个文件的过期时间为72小时,通过在Broker配置文件中设置fileReservedTime来改变过期时间,单位为小时。
代码:DefaultMessageStore#addScheduleTask

  1. private void addScheduleTask() {
  2. //每隔10s调度一次清除文件
  3. this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
  4. @Override
  5. public void run() {
  6. DefaultMessageStore.this.cleanFilesPeriodically();
  7. }
  8. }, 1000 * 60, this.messageStoreConfig.getCleanResourceInterval(), TimeUnit.MILLISECONDS);
  9. ...
  10. }

代码:DefaultMessageStore#cleanFilesPeriodically

  1. private void cleanFilesPeriodically() {
  2. //清除存储文件
  3. this.cleanCommitLogService.run();
  4. //清除消息消费队列文件
  5. this.cleanConsumeQueueService.run();
  6. }

代码:DefaultMessageStore#deleteExpiredFiles

  1. private void deleteExpiredFiles() {
  2. //删除的数量
  3. int deleteCount = 0;
  4. //文件保留的时间
  5. long fileReservedTime = DefaultMessageStore.this.getMessageStoreConfig().getFileReservedTime();
  6. //删除物理文件的间隔
  7. int deletePhysicFilesInterval = DefaultMessageStore.this.getMessageStoreConfig().getDeleteCommitLogFilesInterval();
  8. //线程被占用,第一次拒绝删除后能保留的最大时间,超过该时间,文件将被强制删除
  9. int destroyMapedFileIntervalForcibly = DefaultMessageStore.this.getMessageStoreConfig().getDestroyMapedFileIntervalForcibly();
  10. boolean timeup = this.isTimeToDelete();
  11. boolean spacefull = this.isSpaceToDelete();
  12. boolean manualDelete = this.manualDeleteFileSeveralTimes > 0;
  13. if (timeup || spacefull || manualDelete) {
  14. ...执行删除逻辑
  15. }else{
  16. ...无作为
  17. }

删除文件操作的条件

  1. 指定删除文件的时间点,RocketMQ通过deleteWhen设置一天的固定时间执行一次删除过期文件操作,默认4点
  2. 磁盘空间如果不充足,删除过期文件
  3. 预留,手工触发。

代码:CleanCommitLogService#isSpaceToDelete
当磁盘空间不足时执行删除过期文件

  1. private boolean isSpaceToDelete() {
  2. //磁盘分区的最大使用量
  3. double ratio = DefaultMessageStore.this.getMessageStoreConfig().getDiskMaxUsedSpaceRatio() / 100.0;
  4. //是否需要立即执行删除过期文件操作
  5. cleanImmediately = false;
  6. {
  7. String storePathPhysic = DefaultMessageStore.this.getMessageStoreConfig().getStorePathCommitLog();
  8. //当前CommitLog目录所在的磁盘分区的磁盘使用率
  9. double physicRatio = UtilAll.getDiskPartitionSpaceUsedPercent(storePathPhysic);
  10. //diskSpaceWarningLevelRatio:磁盘使用率警告阈值,默认0.90
  11. if (physicRatio > diskSpaceWarningLevelRatio) {
  12. boolean diskok = DefaultMessageStore.this.runningFlags.getAndMakeDiskFull();
  13. if (diskok) {
  14. DefaultMessageStore.log.error("physic disk maybe full soon " + physicRatio + ", so mark disk full");
  15. }
  16. //diskSpaceCleanForciblyRatio:强制清除阈值,默认0.85
  17. cleanImmediately = true;
  18. } else if (physicRatio > diskSpaceCleanForciblyRatio) {
  19. cleanImmediately = true;
  20. } else {
  21. boolean diskok = DefaultMessageStore.this.runningFlags.getAndMakeDiskOK();
  22. if (!diskok) {
  23. DefaultMessageStore.log.info("physic disk space OK " + physicRatio + ", so mark disk ok");
  24. }
  25. }
  26. if (physicRatio < 0 || physicRatio > ratio) {
  27. DefaultMessageStore.log.info("physic disk maybe full soon, so reclaim space, " + physicRatio);
  28. return true;
  29. }
  30. }

代码:MappedFileQueue#deleteExpiredFileByTime
执行文件销毁和删除

  1. for (int i = 0; i < mfsLength; i++) {
  2. //遍历每隔文件
  3. MappedFile mappedFile = (MappedFile) mfs[i];
  4. //计算文件存活时间
  5. long liveMaxTimestamp = mappedFile.getLastModifiedTimestamp() + expiredTime;
  6. //如果超过72小时,执行文件删除
  7. if (System.currentTimeMillis() >= liveMaxTimestamp || cleanImmediately) {
  8. if (mappedFile.destroy(intervalForcibly)) {
  9. files.add(mappedFile);
  10. deleteCount++;
  11. if (files.size() >= DELETE_FILES_BATCH_MAX) {
  12. break;
  13. }
  14. if (deleteFilesInterval > 0 && (i + 1) < mfsLength) {
  15. try {
  16. Thread.sleep(deleteFilesInterval);
  17. } catch (InterruptedException e) {
  18. }
  19. }
  20. } else {
  21. break;
  22. }
  23. } else {
  24. //avoid deleting files in the middle
  25. break;
  26. }
  27. }

2.4.9 小结

RocketMQ的存储文件包括消息文件(Commitlog)、消息消费队列文件(ConsumerQueue)、Hash索引文件(IndexFile)、监测点文件(checkPoint)、abort(关闭异常文件)。单个消息存储文件、消息消费队列文件、Hash索引文件长度固定以便使用内存映射机制进行文件的读写操作。RocketMQ组织文件以文件的起始偏移量来命令文件,这样根据偏移量能快速定位到真实的物理文件。RocketMQ基于内存映射文件机制提供了同步刷盘和异步刷盘两种机制,异步刷盘是指在消息存储时先追加到内存映射文件,然后启动专门的刷盘线程定时将内存中的文件数据刷写到磁盘。
CommitLog,消息存储文件,RocketMQ为了保证消息发送的高吞吐量,采用单一文件存储所有主题消息,保证消息存储是完全的顺序写,但这样给文件读取带来了不便,为此RocketMQ为了方便消息消费构建了消息消费队列文件,基于主题与队列进行组织,同时RocketMQ为消息实现了Hash索引,可以为消息设置索引键,根据所以能够快速从CommitLog文件中检索消息。
当消息达到CommitLog后,会通过ReputMessageService线程接近实时地将消息转发给消息消费队列文件与索引文件。为了安全起见,RocketMQ引入abort文件,记录Broker的停机是否是正常关闭还是异常关闭,在重启Broker时为了保证CommitLog文件,消息消费队列文件与Hash索引文件的正确性,分别采用不同策略来恢复文件。
RocketMQ不会永久存储消息文件、消息消费队列文件,而是启动文件过期机制并在磁盘空间不足或者默认凌晨4点删除过期文件,文件保存72小时并且在删除文件时并不会判断该消息文件上的消息是否被消费。

2.5 Consumer

2.5.1 消息消费概述

消息消费以组的模式开展,一个消费组内可以包含多个消费者,每一个消费者组可订阅多个主题,消费组之间有ff式和广播模式两种消费模式。集群模式,主题下的同一条消息只允许被其中一个消费者消费。广播模式,主题下的同一条消息,将被集群内的所有消费者消费一次。消息服务器与消费者之间的消息传递也有两种模式:推模式、拉模式。所谓的拉模式,是消费端主动拉起拉消息请求,而推模式是消息达到消息服务器后,推送给消息消费者。RocketMQ消息推模式的实现基于拉模式,在拉模式上包装一层,一个拉取任务完成后开始下一个拉取任务。
集群模式下,多个消费者如何对消息队列进行负载呢?消息队列负载机制遵循一个通用思想:一个消息队列同一个时间只允许被一个消费者消费,一个消费者可以消费多个消息队列。
RocketMQ支持局部顺序消息消费,也就是保证同一个消息队列上的消息顺序消费。不支持消息全局顺序消费,如果要实现某一个主题的全局顺序消费,可以将该主题的队列数设置为1,牺牲高可用性。
###2.5.2 消息消费初探
消息推送模式
RocketMQ-03 - 图66
消息消费重要方法

  1. void sendMessageBack(final MessageExt msg, final int delayLevel, final String brokerName):发送消息确认
  2. Set<MessageQueue> fetchSubscribeMessageQueues(final String topic) :获取消费者对主题分配了那些消息队列
  3. void registerMessageListener(final MessageListenerConcurrently messageListener):注册并发事件监听器
  4. void registerMessageListener(final MessageListenerOrderly messageListener):注册顺序消息事件监听器
  5. void subscribe(final String topic, final String subExpression):基于主题订阅消息,消息过滤使用表达式
  6. void subscribe(final String topic, final String fullClassName,final String filterClassSource):基于主题订阅消息,消息过滤使用类模式
  7. void subscribe(final String topic, final MessageSelector selector) :订阅消息,并指定队列选择器
  8. void unsubscribe(final String topic):取消消息订阅

DefaultMQPushConsumer
RocketMQ-03 - 图67

  1. //消费者组
  2. private String consumerGroup;
  3. //消息消费模式
  4. private MessageModel messageModel = MessageModel.CLUSTERING;
  5. //指定消费开始偏移量(最大偏移量、最小偏移量、启动时间戳)开始消费
  6. private ConsumeFromWhere consumeFromWhere = ConsumeFromWhere.CONSUME_FROM_LAST_OFFSET;
  7. //集群模式下的消息队列负载策略
  8. private AllocateMessageQueueStrategy allocateMessageQueueStrategy;
  9. //订阅信息
  10. private Map<String /* topic */, String /* sub expression */> subscription = new HashMap<String, String>();
  11. //消息业务监听器
  12. private MessageListener messageListener;
  13. //消息消费进度存储器
  14. private OffsetStore offsetStore;
  15. //消费者最小线程数量
  16. private int consumeThreadMin = 20;
  17. //消费者最大线程数量
  18. private int consumeThreadMax = 20;
  19. //并发消息消费时处理队列最大跨度
  20. private int consumeConcurrentlyMaxSpan = 2000;
  21. //每1000次流控后打印流控日志
  22. private int pullThresholdForQueue = 1000;
  23. //推模式下任务间隔时间
  24. private long pullInterval = 0;
  25. //推模式下任务拉取的条数,默认32条
  26. private int pullBatchSize = 32;
  27. //每次传入MessageListener#consumerMessage中消息的数量
  28. private int consumeMessageBatchMaxSize = 1;
  29. //是否每次拉取消息都订阅消息
  30. private boolean postSubscriptionWhenPull = false;
  31. //消息重试次数,-1代表16次
  32. private int maxReconsumeTimes = -1;
  33. //消息消费超时时间
  34. private long consumeTimeout = 15;

2.5.3 消费者启动流程

RocketMQ-03 - 图68
代码:DefaultMQPushConsumerImpl#start

  1. public synchronized void start() throws MQClientException {
  2. switch (this.serviceState) {
  3. case CREATE_JUST:
  4. this.defaultMQPushConsumer.getMessageModel(), this.defaultMQPushConsumer.isUnitMode());
  5. this.serviceState = ServiceState.START_FAILED;
  6. //检查消息者是否合法
  7. this.checkConfig();
  8. //构建主题订阅信息
  9. this.copySubscription();
  10. //设置消费者客户端实例名称为进程ID
  11. if (this.defaultMQPushConsumer.getMessageModel() == MessageModel.CLUSTERING) {
  12. this.defaultMQPushConsumer.changeInstanceNameToPID();
  13. }
  14. //创建MQClient实例
  15. this.mQClientFactory = MQClientManager.getInstance().getAndCreateMQClientInstance(this.defaultMQPushConsumer, this.rpcHook);
  16. //构建rebalanceImpl
  17. this.rebalanceImpl.setConsumerGroup(this.defaultMQPushConsumer.getConsumerGroup());
  18. this.rebalanceImpl.setMessageModel(this.defaultMQPushConsumer.getMessageModel());
  19. this.rebalanceImpl.setAllocateMessageQueueStrategy(this.defaultMQPushConsumer.getAllocateMessageQueueStrategy());
  20. this.rebalanceImpl.setmQClientFactory(this.mQClientFactor
  21. this.pullAPIWrapper = new PullAPIWrapper(
  22. mQClientFactory,
  23. this.defaultMQPushConsumer.getConsumerGroup(), isUnitMode());
  24. this.pullAPIWrapper.registerFilterMessageHook(filterMessageHookLis
  25. if (this.defaultMQPushConsumer.getOffsetStore() != null) {
  26. this.offsetStore = this.defaultMQPushConsumer.getOffsetStore();
  27. } else {
  28. switch (this.defaultMQPushConsumer.getMessageModel()) {
  29. case BROADCASTING: //消息消费广播模式,将消费进度保存在本地
  30. this.offsetStore = new LocalFileOffsetStore(this.mQClientFactory, this.defaultMQPushConsumer.getConsumerGroup());
  31. break;
  32. case CLUSTERING: //消息消费集群模式,将消费进度保存在远端Broker
  33. this.offsetStore = new RemoteBrokerOffsetStore(this.mQClientFactory, this.defaultMQPushConsumer.getConsumerGroup());
  34. break;
  35. default:
  36. break;
  37. }
  38. this.defaultMQPushConsumer.setOffsetStore(this.offsetStore);
  39. }
  40. this.offsetStore.load
  41. //创建顺序消息消费服务
  42. if (this.getMessageListenerInner() instanceof MessageListenerOrderly) {
  43. this.consumeOrderly = true;
  44. this.consumeMessageService =
  45. new ConsumeMessageOrderlyService(this, (MessageListenerOrderly) this.getMessageListenerInner());
  46. //创建并发消息消费服务
  47. } else if (this.getMessageListenerInner() instanceof MessageListenerConcurrently) {
  48. this.consumeOrderly = false;
  49. this.consumeMessageService =
  50. new ConsumeMessageConcurrentlyService(this, (MessageListenerConcurrently) this.getMessageListenerInner());
  51. }
  52. //消息消费服务启动
  53. this.consumeMessageService.start();
  54. //注册消费者实例
  55. boolean registerOK = mQClientFactory.registerConsumer(this.defaultMQPushConsumer.getConsumerGroup(), this);
  56. if (!registerOK) {
  57. this.serviceState = ServiceState.CREATE_JUST;
  58. this.consumeMessageService.shutdown();
  59. throw new MQClientException("The consumer group[" + this.defaultMQPushConsumer.getConsumerGroup()
  60. + "] has been created before, specify another name please." + FAQUrl.suggestTodo(FAQUrl.GROUP_NAME_DUPLICATE_URL),
  61. null);
  62. //启动消费者客户端
  63. mQClientFactory.start();
  64. log.info("the consumer [{}] start OK.", this.defaultMQPushConsumer.getConsumerGroup());
  65. this.serviceState = ServiceState.RUNNING;
  66. break;
  67. case RUNNING:
  68. case START_FAILED:
  69. case SHUTDOWN_ALREADY:
  70. throw new MQClientException("The PushConsumer service state not OK, maybe started once, "
  71. + this.serviceState
  72. + FAQUrl.suggestTodo(FAQUrl.CLIENT_SERVICE_NOT_OK),
  73. null);
  74. default:
  75. break;
  76. }
  77. this.updateTopicSubscribeInfoWhenSubscriptionChanged();
  78. this.mQClientFactory.checkClientInBroker();
  79. this.mQClientFactory.sendHeartbeatToAllBrokerWithLock();
  80. this.mQClientFactory.rebalanceImmediately();
  81. }

2.5.4 消息拉取

消息消费模式有两种模式:广播模式与集群模式。广播模式比较简单,每一个消费者需要拉取订阅主题下所有队列的消息。本文重点讲解集群模式。在集群模式下,同一个消费者组内有多个消息消费者,同一个主题存在多个消费队列,消费者通过负载均衡的方式消费消息。
消息队列负载均衡,通常的作法是一个消息队列在同一个时间只允许被一个消费消费者消费,一个消息消费者可以同时消费多个消息队列。

1)PullMessageService实现机制

从MQClientInstance的启动流程中可以看出,RocketMQ使用一个单独的线程PullMessageService来负责消息的拉取。
RocketMQ-03 - 图69
代码:PullMessageService#run

  1. public void run() {
  2. log.info(this.getServiceName() + " service started");
  3. //循环拉取消息
  4. while (!this.isStopped()) {
  5. try {
  6. //从请求队列中获取拉取消息请求
  7. PullRequest pullRequest = this.pullRequestQueue.take();
  8. //拉取消息
  9. this.pullMessage(pullRequest);
  10. } catch (InterruptedException ignored) {
  11. } catch (Exception e) {
  12. log.error("Pull Message Service Run Method exception", e);
  13. }
  14. }
  15. log.info(this.getServiceName() + " service end");
  16. }

PullRequest
RocketMQ-03 - 图70

  1. private String consumerGroup; //消费者组
  2. private MessageQueue messageQueue; //待拉取消息队列
  3. private ProcessQueue processQueue; //消息处理队列
  4. private long nextOffset; //待拉取的MessageQueue偏移量
  5. private boolean lockedFirst = false; //是否被锁定

代码:PullMessageService#pullMessage

  1. private void pullMessage(final PullRequest pullRequest) {
  2. //获得消费者实例
  3. final MQConsumerInner consumer = this.mQClientFactory.selectConsumer(pullRequest.getConsumerGroup());
  4. if (consumer != null) {
  5. //强转为推送模式消费者
  6. DefaultMQPushConsumerImpl impl = (DefaultMQPushConsumerImpl) consumer;
  7. //推送消息
  8. impl.pullMessage(pullRequest);
  9. } else {
  10. log.warn("No matched consumer for the PullRequest {}, drop it", pullRequest);
  11. }
  12. }

2)ProcessQueue实现机制
ProcessQueue是MessageQueue在消费端的重现、快照。PullMessageService从消息服务器默认每次拉取32条消息,按照消息的队列偏移量顺序存放在ProcessQueue中,PullMessageService然后将消息提交到消费者消费线程池,消息成功消费后从ProcessQueue中移除。
RocketMQ-03 - 图71
属性

  1. //消息容器
  2. private final TreeMap<Long, MessageExt> msgTreeMap = new TreeMap<Long, MessageExt>();
  3. //读写锁
  4. private final ReadWriteLock lockTreeMap = new ReentrantReadWriteLock();
  5. //ProcessQueue总消息树
  6. private final AtomicLong msgCount = new AtomicLong();
  7. //ProcessQueue队列最大偏移量
  8. private volatile long queueOffsetMax = 0L;
  9. //当前ProcessQueue是否被丢弃
  10. private volatile boolean dropped = false;
  11. //上一次拉取时间戳
  12. private volatile long lastPullTimestamp = System.currentTimeMillis();
  13. //上一次消费时间戳
  14. private volatile long lastConsumeTimestamp = System.currentTimeMillis();

方法

  1. //移除消费超时消息
  2. public void cleanExpiredMsg(DefaultMQPushConsumer pushConsumer)
  3. //添加消息
  4. public boolean putMessage(final List<MessageExt> msgs)
  5. //获取消息最大间隔
  6. public long getMaxSpan()
  7. //移除消息
  8. public long removeMessage(final List<MessageExt> msgs)
  9. //将consumingMsgOrderlyTreeMap中消息重新放在msgTreeMap,并清空consumingMsgOrderlyTreeMap
  10. public void rollback()
  11. //将consumingMsgOrderlyTreeMap消息清除,表示成功处理该批消息
  12. public long commit()
  13. //重新处理该批消息
  14. public void makeMessageToCosumeAgain(List<MessageExt> msgs)
  15. //从processQueue中取出batchSize条消息
  16. public List<MessageExt> takeMessags(final int batchSize)

3)消息拉取基本流程

1.客户端发起拉取请求
RocketMQ-03 - 图72
代码:DefaultMQPushConsumerImpl#pullMessage
  1. public void pullMessage(final PullRequest pullRequest) {
  2. //从pullRequest获得ProcessQueue
  3. final ProcessQueue processQueue = pullRequest.getProcessQueue();
  4. //如果处理队列被丢弃,直接返回
  5. if (processQueue.isDropped()) {
  6. log.info("the pull request[{}] is dropped.", pullRequest.toString());
  7. return;
  8. }
  9. //如果处理队列未被丢弃,更新时间戳
  10. pullRequest.getProcessQueue().setLastPullTimestamp(System.currentTimeMillis());
  11. try {
  12. this.makeSureStateOK();
  13. } catch (MQClientException e) {
  14. log.warn("pullMessage exception, consumer state not ok", e);
  15. this.executePullRequestLater(pullRequest, PULL_TIME_DELAY_MILLS_WHEN_EXCEPTION);
  16. return;
  17. }
  18. //如果处理队列被挂起,延迟1s后再执行
  19. if (this.isPause()) {
  20. log.warn("consumer was paused, execute pull request later. instanceName={}, group={}", this.defaultMQPushConsumer.getInstanceName(), this.defaultMQPushConsumer.getConsumerGroup());
  21. this.executePullRequestLater(pullRequest, PULL_TIME_DELAY_MILLS_WHEN_SUSPEND);
  22. return;
  23. }
  24. //获得最大待处理消息数量
  25. long cachedMessageCount = processQueue.getMsgCount().get();
  26. //获得最大待处理消息大小
  27. long cachedMessageSizeInMiB = processQueue.getMsgSize().get() / (1024 * 1024);
  28. //从数量进行流控
  29. if (cachedMessageCount > this.defaultMQPushConsumer.getPullThresholdForQueue()) {
  30. this.executePullRequestLater(pullRequest, PULL_TIME_DELAY_MILLS_WHEN_FLOW_CONTROL);
  31. if ((queueFlowControlTimes++ % 1000) == 0) {
  32. log.warn(
  33. "the cached message count exceeds the threshold {}, so do flow control, minOffset={}, maxOffset={}, count={}, size={} MiB, pullRequest={}, flowControlTimes={}",
  34. this.defaultMQPushConsumer.getPullThresholdForQueue(), processQueue.getMsgTreeMap().firstKey(), processQueue.getMsgTreeMap().lastKey(), cachedMessageCount, cachedMessageSizeInMiB, pullRequest, queueFlowControlTimes);
  35. }
  36. return;
  37. }
  38. //从消息大小进行流控
  39. if (cachedMessageSizeInMiB > this.defaultMQPushConsumer.getPullThresholdSizeForQueue()) {
  40. this.executePullRequestLater(pullRequest, PULL_TIME_DELAY_MILLS_WHEN_FLOW_CONTROL);
  41. if ((queueFlowControlTimes++ % 1000) == 0) {
  42. log.warn(
  43. "the cached message size exceeds the threshold {} MiB, so do flow control, minOffset={}, maxOffset={}, count={}, size={} MiB, pullRequest={}, flowControlTimes={}",
  44. this.defaultMQPushConsumer.getPullThresholdSizeForQueue(), processQueue.getMsgTreeMap().firstKey(), processQueue.getMsgTreeMap().lastKey(), cachedMessageCount, cachedMessageSizeInMiB, pullRequest, queueFlowControlTimes);
  45. }
  46. return;
  47. }
  48. //获得订阅信息
  49. final SubscriptionData subscriptionData = this.rebalanceImpl.getSubscriptionInner().get(pullRequest.getMessageQueue().getTopic());
  50. if (null == subscriptionData) {
  51. this.executePullRequestLater(pullRequest, PULL_TIME_DELAY_MILLS_WHEN_EXCEPTION);
  52. log.warn("find the consumer's subscription failed, {}", pullRequest);
  53. return;
  54. //与服务端交互,获取消息
  55. this.pullAPIWrapper.pullKernelImpl(
  56. pullRequest.getMessageQueue(),
  57. subExpression,
  58. subscriptionData.getExpressionType(),
  59. subscriptionData.getSubVersion(),
  60. pullRequest.getNextOffset(),
  61. this.defaultMQPushConsumer.getPullBatchSize(),
  62. sysFlag,
  63. commitOffsetValue,
  64. BROKER_SUSPEND_MAX_TIME_MILLIS,
  65. CONSUMER_TIMEOUT_MILLIS_WHEN_SUSPEND,
  66. CommunicationMode.ASYNC,
  67. pullCallback
  68. );
  69. }
2.消息服务端Broker组装消息
RocketMQ-03 - 图73
代码:PullMessageProcessor#processRequest
  1. //构建消息过滤器
  2. MessageFilter messageFilter;
  3. if (this.brokerController.getBrokerConfig().isFilterSupportRetry()) {
  4. messageFilter = new ExpressionForRetryMessageFilter(subscriptionData, consumerFilterData,
  5. this.brokerController.getConsumerFilterManager());
  6. } else {
  7. messageFilter = new ExpressionMessageFilter(subscriptionData, consumerFilterData,
  8. this.brokerController.getConsumerFilterManager());
  9. }
  10. //调用MessageStore.getMessage查找消息
  11. final GetMessageResult getMessageResult =
  12. this.brokerController.getMessageStore().getMessage(
  13. requestHeader.getConsumerGroup(), //消费组名称
  14. requestHeader.getTopic(), //主题名称
  15. requestHeader.getQueueId(), //队列ID
  16. requestHeader.getQueueOffset(), //待拉取偏移量
  17. requestHeader.getMaxMsgNums(), //最大拉取消息条数
  18. messageFilter //消息过滤器
  19. );

代码:DefaultMessageStore#getMessage

  1. GetMessageStatus status = GetMessageStatus.NO_MESSAGE_IN_QUEUE;
  2. long nextBeginOffset = offset; //查找下一次队列偏移量
  3. long minOffset = 0; //当前消息队列最小偏移量
  4. long maxOffset = 0; //当前消息队列最大偏移量
  5. GetMessageResult getResult = new GetMessageResult();
  6. final long maxOffsetPy = this.commitLog.getMaxOffset(); //当前commitLog最大偏移量
  7. //根据主题名称和队列编号获取消息消费队列
  8. ConsumeQueue consumeQueue = findConsumeQueue(topic, queueId);
  9. ...
  10. minOffset = consumeQueue.getMinOffsetInQueue();
  11. maxOffset = consumeQueue.getMaxOffsetInQueue();
  12. //消息偏移量异常情况校对下一次拉取偏移量
  13. if (maxOffset == 0) { //表示当前消息队列中没有消息
  14. status = GetMessageStatus.NO_MESSAGE_IN_QUEUE;
  15. nextBeginOffset = nextOffsetCorrection(offset, 0);
  16. } else if (offset < minOffset) { //待拉取消息的偏移量小于队列的其实偏移量
  17. status = GetMessageStatus.OFFSET_TOO_SMALL;
  18. nextBeginOffset = nextOffsetCorrection(offset, minOffset);
  19. } else if (offset == maxOffset) { //待拉取偏移量为队列最大偏移量
  20. status = GetMessageStatus.OFFSET_OVERFLOW_ONE;
  21. nextBeginOffset = nextOffsetCorrection(offset, offset);
  22. } else if (offset > maxOffset) { //偏移量越界
  23. status = GetMessageStatus.OFFSET_OVERFLOW_BADLY;
  24. if (0 == minOffset) {
  25. nextBeginOffset = nextOffsetCorrection(offset, minOffset);
  26. } else {
  27. nextBeginOffset = nextOffsetCorrection(offset, maxOffset);
  28. }
  29. }
  30. ...
  31. //根据偏移量从CommitLog中拉取32条消息
  32. SelectMappedBufferResult selectResult = this.commitLog.getMessage(offsetPy, sizePy);

代码:PullMessageProcessor#processRequest

  1. //根据拉取结果填充responseHeader
  2. response.setRemark(getMessageResult.getStatus().name());
  3. responseHeader.setNextBeginOffset(getMessageResult.getNextBeginOffset());
  4. responseHeader.setMinOffset(getMessageResult.getMinOffset());
  5. responseHeader.setMaxOffset(getMessageResult.getMaxOffset());
  6. //判断如果存在主从同步慢,设置下一次拉取任务的ID为主节点
  7. switch (this.brokerController.getMessageStoreConfig().getBrokerRole()) {
  8. case ASYNC_MASTER:
  9. case SYNC_MASTER:
  10. break;
  11. case SLAVE:
  12. if (!this.brokerController.getBrokerConfig().isSlaveReadEnable()) {
  13. response.setCode(ResponseCode.PULL_RETRY_IMMEDIATELY);
  14. responseHeader.setSuggestWhichBrokerId(MixAll.MASTER_ID);
  15. }
  16. break;
  17. }
  18. ...
  19. //GetMessageResult与Response的Code转换
  20. switch (getMessageResult.getStatus()) {
  21. case FOUND: //成功
  22. response.setCode(ResponseCode.SUCCESS);
  23. break;
  24. case MESSAGE_WAS_REMOVING: //消息存放在下一个commitLog中
  25. response.setCode(ResponseCode.PULL_RETRY_IMMEDIATELY); //消息重试
  26. break;
  27. case NO_MATCHED_LOGIC_QUEUE: //未找到队列
  28. case NO_MESSAGE_IN_QUEUE: //队列中未包含消息
  29. if (0 != requestHeader.getQueueOffset()) {
  30. response.setCode(ResponseCode.PULL_OFFSET_MOVED);
  31. requestHeader.getQueueOffset(),
  32. getMessageResult.getNextBeginOffset(),
  33. requestHeader.getTopic(),
  34. requestHeader.getQueueId(),
  35. requestHeader.getConsumerGroup()
  36. );
  37. } else {
  38. response.setCode(ResponseCode.PULL_NOT_FOUND);
  39. }
  40. break;
  41. case NO_MATCHED_MESSAGE: //未找到消息
  42. response.setCode(ResponseCode.PULL_RETRY_IMMEDIATELY);
  43. break;
  44. case OFFSET_FOUND_NULL: //消息物理偏移量为空
  45. response.setCode(ResponseCode.PULL_NOT_FOUND);
  46. break;
  47. case OFFSET_OVERFLOW_BADLY: //offset越界
  48. response.setCode(ResponseCode.PULL_OFFSET_MOVED);
  49. // XXX: warn and notify me
  50. log.info("the request offset: {} over flow badly, broker max offset: {}, consumer: {}",
  51. requestHeader.getQueueOffset(), getMessageResult.getMaxOffset(), channel.remoteAddress());
  52. break;
  53. case OFFSET_OVERFLOW_ONE: //offset在队列中未找到
  54. response.setCode(ResponseCode.PULL_NOT_FOUND);
  55. break;
  56. case OFFSET_TOO_SMALL: //offset未在队列中
  57. response.setCode(ResponseCode.PULL_OFFSET_MOVED);
  58. requestHeader.getConsumerGroup(),
  59. requestHeader.getTopic(),
  60. requestHeader.getQueueOffset(),
  61. getMessageResult.getMinOffset(), channel.remoteAddress());
  62. break;
  63. default:
  64. assert false;
  65. break;
  66. }
  67. ...
  68. //如果CommitLog标记可用,并且当前Broker为主节点,则更新消息消费进度
  69. boolean storeOffsetEnable = brokerAllowSuspend;
  70. storeOffsetEnable = storeOffsetEnable && hasCommitOffsetFlag;
  71. storeOffsetEnable = storeOffsetEnable
  72. && this.brokerController.getMessageStoreConfig().getBrokerRole() != BrokerRole.SLAVE;
  73. if (storeOffsetEnable) {
  74. this.brokerController.getConsumerOffsetManager().commitOffset(RemotingHelper.parseChannelRemoteAddr(channel),
  75. requestHeader.getConsumerGroup(), requestHeader.getTopic(), requestHeader.getQueueId(), requestHeader.getCommitOffset());
  76. }
3.消息拉取客户端处理消息
RocketMQ-03 - 图74
代码:MQClientAPIImpl#processPullResponse
  1. private PullResult processPullResponse(
  2. final RemotingCommand response) throws MQBrokerException, RemotingCommandException {
  3. PullStatus pullStatus = PullStatus.NO_NEW_MSG;
  4. //判断响应结果
  5. switch (response.getCode()) {
  6. case ResponseCode.SUCCESS:
  7. pullStatus = PullStatus.FOUND;
  8. break;
  9. case ResponseCode.PULL_NOT_FOUND:
  10. pullStatus = PullStatus.NO_NEW_MSG;
  11. break;
  12. case ResponseCode.PULL_RETRY_IMMEDIATELY:
  13. pullStatus = PullStatus.NO_MATCHED_MSG;
  14. break;
  15. case ResponseCode.PULL_OFFSET_MOVED:
  16. pullStatus = PullStatus.OFFSET_ILLEGAL;
  17. break;
  18. default:
  19. throw new MQBrokerException(response.getCode(), response.getRemark());
  20. }
  21. //解码响应头
  22. PullMessageResponseHeader responseHeader =
  23. (PullMessageResponseHeader) response.decodeCommandCustomHeader(PullMessageResponseHeader.class);
  24. //封装PullResultExt返回
  25. return new PullResultExt(pullStatus, responseHeader.getNextBeginOffset(), responseHeader.getMinOffset(),
  26. responseHeader.getMaxOffset(), null, responseHeader.getSuggestWhichBrokerId(), response.getBody());
  27. }

PullResult类

  1. private final PullStatus pullStatus; //拉取结果
  2. private final long nextBeginOffset; //下次拉取偏移量
  3. private final long minOffset; //消息队列最小偏移量
  4. private final long maxOffset; //消息队列最大偏移量
  5. private List<MessageExt> msgFoundList; //拉取的消息列表

RocketMQ-03 - 图75
代码:DefaultMQPushConsumerImpl$PullCallback#OnSuccess

  1. //将拉取到的消息存入processQueue
  2. boolean dispatchToConsume = processQueue.putMessage(pullResult.getMsgFoundList());
  3. //将processQueue提交到consumeMessageService中供消费者消费
  4. DefaultMQPushConsumerImpl.this.consumeMessageService.submitConsumeRequest(
  5. pullResult.getMsgFoundList(),
  6. processQueue,
  7. pullRequest.getMessageQueue(),
  8. dispatchToConsume);
  9. //如果pullInterval大于0,则等待pullInterval毫秒后将pullRequest对象放入到PullMessageService中的pullRequestQueue队列中
  10. if (DefaultMQPushConsumerImpl.this.defaultMQPushConsumer.getPullInterval() > 0) {
  11. DefaultMQPushConsumerImpl.this.executePullRequestLater(pullRequest,
  12. DefaultMQPushConsumerImpl.this.defaultMQPushConsumer.getPullInterval());
  13. } else {
  14. DefaultMQPushConsumerImpl.this.executePullRequestImmediately(pullRequest);
  15. }

4.消息拉取总结

RocketMQ-03 - 图76

4)消息拉取长轮询机制分析

RocketMQ未真正实现消息推模式,而是消费者主动向消息服务器拉取消息,RocketMQ推模式是循环向消息服务端发起消息拉取请求,如果消息消费者向RocketMQ拉取消息时,消息未到达消费队列时,如果不启用长轮询机制,则会在服务端等待shortPollingTimeMills时间后(挂起)再去判断消息是否已经到达指定消息队列,如果消息仍未到达则提示拉取消息客户端PULL—NOT—FOUND(消息不存在);如果开启长轮询模式,RocketMQ一方面会每隔5s轮询检查一次消息是否可达,同时一有消息达到后立马通知挂起线程再次验证消息是否是自己感兴趣的消息,如果是则从CommitLog文件中提取消息返回给消息拉取客户端,否则直到挂起超时,超时时间由消息拉取方在消息拉取是封装在请求参数中,PUSH模式为15s,PULL模式通过DefaultMQPullConsumer#setBrokerSuspendMaxTimeMillis设置。RocketMQ通过在Broker客户端配置longPollingEnable为true来开启长轮询模式。
代码:PullMessageProcessor#processRequest

  1. //当没有拉取到消息时,通过长轮询方式继续拉取消息
  2. case ResponseCode.PULL_NOT_FOUND:
  3. if (brokerAllowSuspend && hasSuspendFlag) {
  4. long pollingTimeMills = suspendTimeoutMillisLong;
  5. if (!this.brokerController.getBrokerConfig().isLongPollingEnable()) {
  6. pollingTimeMills = this.brokerController.getBrokerConfig().getShortPollingTimeMills();
  7. }
  8. String topic = requestHeader.getTopic();
  9. long offset = requestHeader.getQueueOffset();
  10. int queueId = requestHeader.getQueueId();
  11. //构建拉取请求对象
  12. PullRequest pullRequest = new PullRequest(request, channel, pollingTimeMills,
  13. this.brokerController.getMessageStore().now(), offset, subscriptionData, messageFilter);
  14. //处理拉取请求
  15. this.brokerController.getPullRequestHoldService().suspendPullRequest(topic, queueId, pullRequest);
  16. response = null;
  17. break;
  18. }

PullRequestHoldService方式实现长轮询
代码:PullRequestHoldService#suspendPullRequest

  1. //将拉取消息请求,放置在ManyPullRequest集合中
  2. public void suspendPullRequest(final String topic, final int queueId, final PullRequest pullRequest) {
  3. String key = this.buildKey(topic, queueId);
  4. ManyPullRequest mpr = this.pullRequestTable.get(key);
  5. if (null == mpr) {
  6. mpr = new ManyPullRequest();
  7. ManyPullRequest prev = this.pullRequestTable.putIfAbsent(key, mpr);
  8. if (prev != null) {
  9. mpr = prev;
  10. }
  11. }
  12. mpr.addPullRequest(pullRequest);
  13. }

代码:PullRequestHoldService#run

  1. public void run() {
  2. log.info("{} service started", this.getServiceName());
  3. while (!this.isStopped()) {
  4. try {
  5. //如果开启长轮询每隔5秒判断消息是否到达
  6. if (this.brokerController.getBrokerConfig().isLongPollingEnable()) {
  7. this.waitForRunning(5 * 1000);
  8. } else {
  9. //没有开启长轮询,每隔1s再次尝试
  10. this.waitForRunning(this.brokerController.getBrokerConfig().getShortPollingTimeMills());
  11. }
  12. long beginLockTimestamp = this.systemClock.now();
  13. this.checkHoldRequest();
  14. long costTime = this.systemClock.now() - beginLockTimestamp;
  15. if (costTime > 5 * 1000) {
  16. log.info("[NOTIFYME] check hold request cost {} ms.", costTime);
  17. }
  18. } catch (Throwable e) {
  19. log.warn(this.getServiceName() + " service has exception. ", e);
  20. }
  21. }
  22. log.info("{} service end", this.getServiceName());
  23. }

代码:PullRequestHoldService#checkHoldRequest

  1. //遍历拉取任务
  2. private void checkHoldRequest() {
  3. for (String key : this.pullRequestTable.keySet()) {
  4. String[] kArray = key.split(TOPIC_QUEUEID_SEPARATOR);
  5. if (2 == kArray.length) {
  6. String topic = kArray[0];
  7. int queueId = Integer.parseInt(kArray[1]);
  8. //获得消息偏移量
  9. final long offset = this.brokerController.getMessageStore().getMaxOffsetInQueue(topic, queueId);
  10. try {
  11. //通知有消息达到
  12. this.notifyMessageArriving(topic, queueId, offset);
  13. } catch (Throwable e) {
  14. log.error("check hold request failed. topic={}, queueId={}", topic, queueId, e);
  15. }
  16. }
  17. }
  18. }

代码:PullRequestHoldService#notifyMessageArriving

  1. //如果拉取消息偏移大于请求偏移量,如果消息匹配调用executeRequestWhenWakeup处理消息
  2. if (newestOffset > request.getPullFromThisOffset()) {
  3. boolean match = request.getMessageFilter().isMatchedByConsumeQueue(tagsCode,
  4. new ConsumeQueueExt.CqExtUnit(tagsCode, msgStoreTime, filterBitMap));
  5. // match by bit map, need eval again when properties is not null.
  6. if (match && properties != null) {
  7. match = request.getMessageFilter().isMatchedByCommitLog(null, properties);
  8. }
  9. if (match) {
  10. try {
  11. this.brokerController.getPullMessageProcessor().executeRequestWhenWakeup(request.getClientChannel(),
  12. request.getRequestCommand());
  13. } catch (Throwable e) {
  14. log.error("execute request when wakeup failed.", e);
  15. }
  16. continue;
  17. }
  18. }
  19. //如果过期时间超时,则不继续等待将直接返回给客户端消息未找到
  20. if (System.currentTimeMillis() >= (request.getSuspendTimestamp() + request.getTimeoutMillis())) {
  21. try {
  22. this.brokerController.getPullMessageProcessor().executeRequestWhenWakeup(request.getClientChannel(),
  23. request.getRequestCommand());
  24. } catch (Throwable e) {
  25. log.error("execute request when wakeup failed.", e);
  26. }
  27. continue;
  28. }

如果开启了长轮询机制,PullRequestHoldService会每隔5s被唤醒去尝试检测是否有新的消息的到来才给客户端响应,或者直到超时才给客户端进行响应,消息实时性比较差,为了避免这种情况,RocketMQ引入另外一种机制:当消息到达时唤醒挂起线程触发一次检查。
DefaultMessageStore$ReputMessageService机制
代码:DefaultMessageStore#start

  1. //长轮询入口
  2. this.reputMessageService.setReputFromOffset(maxPhysicalPosInLogicQueue);
  3. this.reputMessageService.start();

代码:DefaultMessageStore$ReputMessageService#run

  1. public void run() {
  2. DefaultMessageStore.log.info(this.getServiceName() + " service started");
  3. while (!this.isStopped()) {
  4. try {
  5. Thread.sleep(1);
  6. //长轮询核心逻辑代码入口
  7. this.doReput();
  8. } catch (Exception e) {
  9. DefaultMessageStore.log.warn(this.getServiceName() + " service has exception. ", e);
  10. }
  11. }
  12. DefaultMessageStore.log.info(this.getServiceName() + " service end");
  13. }

代码:DefaultMessageStore$ReputMessageService#deReput

  1. //当新消息达到是,进行通知监听器进行处理
  2. if (BrokerRole.SLAVE != DefaultMessageStore.this.getMessageStoreConfig().getBrokerRole()
  3. && DefaultMessageStore.this.brokerConfig.isLongPollingEnable()) {
  4. DefaultMessageStore.this.messageArrivingListener.arriving(dispatchRequest.getTopic(),
  5. dispatchRequest.getQueueId(), dispatchRequest.getConsumeQueueOffset() + 1,
  6. dispatchRequest.getTagsCode(), dispatchRequest.getStoreTimestamp(),
  7. dispatchRequest.getBitMap(), dispatchRequest.getPropertiesMap());
  8. }

代码:NotifyMessageArrivingListener#arriving

  1. public void arriving(String topic, int queueId, long logicOffset, long tagsCode,
  2. long msgStoreTime, byte[] filterBitMap, Map<String, String> properties) {
  3. this.pullRequestHoldService.notifyMessageArriving(topic, queueId, logicOffset, tagsCode,
  4. msgStoreTime, filterBitMap, properties);
  5. }

2.5.5 消息队列负载与重新分布机制

RocketMQ消息队列重新分配是由RebalanceService线程来实现。一个MQClientInstance持有一个RebalanceService实现,并随着MQClientInstance的启动而启动。
代码:RebalanceService#run

  1. public void run() {
  2. log.info(this.getServiceName() + " service started");
  3. //RebalanceService线程默认每隔20s执行一次mqClientFactory.doRebalance方法
  4. while (!this.isStopped()) {
  5. this.waitForRunning(waitInterval);
  6. this.mqClientFactory.doRebalance();
  7. }
  8. log.info(this.getServiceName() + " service end");
  9. }

代码:MQClientInstance#doRebalance

  1. public void doRebalance() {
  2. //MQClientInstance遍历以注册的消费者,对消费者执行doRebalance()方法
  3. for (Map.Entry<String, MQConsumerInner> entry : this.consumerTable.entrySet()) {
  4. MQConsumerInner impl = entry.getValue();
  5. if (impl != null) {
  6. try {
  7. impl.doRebalance();
  8. } catch (Throwable e) {
  9. log.error("doRebalance exception", e);
  10. }
  11. }
  12. }
  13. }

代码:RebalanceImpl#doRebalance

  1. //遍历订阅消息对每个主题的订阅的队列进行重新负载
  2. public void doRebalance(final boolean isOrder) {
  3. Map<String, SubscriptionData> subTable = this.getSubscriptionInner();
  4. if (subTable != null) {
  5. for (final Map.Entry<String, SubscriptionData> entry : subTable.entrySet()) {
  6. final String topic = entry.getKey();
  7. try {
  8. this.rebalanceByTopic(topic, isOrder);
  9. } catch (Throwable e) {
  10. if (!topic.startsWith(MixAll.RETRY_GROUP_TOPIC_PREFIX)) {
  11. log.warn("rebalanceByTopic Exception", e);
  12. }
  13. }
  14. }
  15. }
  16. this.truncateMessageQueueNotMyTopic();
  17. }

代码:RebalanceImpl#rebalanceByTopic

  1. //从主题订阅消息缓存表中获取主题的队列信息
  2. Set<MessageQueue> mqSet = this.topicSubscribeInfoTable.get(topic);
  3. //查找该主题订阅组所有的消费者ID
  4. List<String> cidAll = this.mQClientFactory.findConsumerIdList(topic, consumerGroup);
  5. //给消费者重新分配队列
  6. if (mqSet != null && cidAll != null) {
  7. List<MessageQueue> mqAll = new ArrayList<MessageQueue>();
  8. mqAll.addAll(mqSet);
  9. Collections.sort(mqAll);
  10. Collections.sort(cidAll);
  11. AllocateMessageQueueStrategy strategy = this.allocateMessageQueueStrategy;
  12. List<MessageQueue> allocateResult = null;
  13. try {
  14. allocateResult = strategy.allocate(
  15. this.consumerGroup,
  16. this.mQClientFactory.getClientId(),
  17. mqAll,
  18. cidAll);
  19. } catch (Throwable e) {
  20. log.error("AllocateMessageQueueStrategy.allocate Exception. allocateMessageQueueStrategyName={}", strategy.getName(),
  21. e);
  22. return;
  23. }

RocketMQ默认提供5中负载均衡分配算法

  1. AllocateMessageQueueAveragely:平均分配
  2. 举例:8个队列q1,q2,q3,q4,q5,a6,q7,q8,消费者3个:c1,c2,c3
  3. 分配如下:
  4. c1:q1,q2,q3
  5. c2:q4,q5,a6
  6. c3:q7,q8
  7. AllocateMessageQueueAveragelyByCircle:平均轮询分配
  8. 举例:8个队列q1,q2,q3,q4,q5,a6,q7,q8,消费者3个:c1,c2,c3
  9. 分配如下:
  10. c1:q1,q4,q7
  11. c2:q2,q5,a8
  12. c3:q3,q6

注意:消息队列的分配遵循一个消费者可以分配到多个队列,但同一个消息队列只会分配给一个消费者,故如果出现消费者个数大于消息队列数量,则有些消费者无法消费消息。

2.5.6 消息消费过程

PullMessageService负责对消息队列进行消息拉取,从远端服务器拉取消息后将消息存储ProcessQueue消息队列处理队列中,然后调用ConsumeMessageService#submitConsumeRequest方法进行消息消费,使用线程池来消费消息,确保了消息拉取与消息消费的解耦。ConsumeMessageService支持顺序消息和并发消息,核心类图如下:
RocketMQ-03 - 图77
并发消息消费
代码:ConsumeMessageConcurrentlyService#submitConsumeRequest

  1. //消息批次单次
  2. final int consumeBatchSize = this.defaultMQPushConsumer.getConsumeMessageBatchMaxSize();
  3. //msgs.size()默认最多为32条。
  4. //如果msgs.size()小于consumeBatchSize,则直接将拉取到的消息放入到consumeRequest,然后将consumeRequest提交到消费者线程池中
  5. if (msgs.size() <= consumeBatchSize) {
  6. ConsumeRequest consumeRequest = new ConsumeRequest(msgs, processQueue, messageQueue);
  7. try {
  8. this.consumeExecutor.submit(consumeRequest);
  9. } catch (RejectedExecutionException e) {
  10. this.submitConsumeRequestLater(consumeRequest);
  11. }
  12. }else{ //如果拉取的消息条数大于consumeBatchSize,则对拉取消息进行分页
  13. for (int total = 0; total < msgs.size(); ) {
  14. List<MessageExt> msgThis = new ArrayList<MessageExt>(consumeBatchSize);
  15. for (int i = 0; i < consumeBatchSize; i++, total++) {
  16. if (total < msgs.size()) {
  17. msgThis.add(msgs.get(total));
  18. } else {
  19. break;
  20. }
  21. ConsumeRequest consumeRequest = new ConsumeRequest(msgThis, processQueue, messageQueue);
  22. try {
  23. this.consumeExecutor.submit(consumeRequest);
  24. } catch (RejectedExecutionException e) {
  25. for (; total < msgs.size(); total++) {
  26. msgThis.add(msgs.get(total));
  27. this.submitConsumeRequestLater(consumeRequest);
  28. }
  29. }
  30. }

代码:ConsumeMessageConcurrentlyService$ConsumeRequest#run

  1. //检查processQueue的dropped,如果为true,则停止该队列消费。
  2. if (this.processQueue.isDropped()) {
  3. log.info("the message queue not be able to consume, because it's dropped. group={} {}", ConsumeMessageConcurrentlyService.this.consumerGroup, this.messageQueue);
  4. return;
  5. }
  6. ...
  7. //执行消息处理的钩子函数
  8. if (ConsumeMessageConcurrentlyService.this.defaultMQPushConsumerImpl.hasHook()) {
  9. consumeMessageContext = new ConsumeMessageContext();
  10. consumeMessageContext.setNamespace(defaultMQPushConsumer.getNamespace());
  11. consumeMessageContext.setConsumerGroup(defaultMQPushConsumer.getConsumerGroup());
  12. consumeMessageContext.setProps(new HashMap<String, String>());
  13. consumeMessageContext.setMq(messageQueue);
  14. consumeMessageContext.setMsgList(msgs);
  15. consumeMessageContext.setSuccess(false);
  16. ConsumeMessageConcurrentlyService.this.defaultMQPushConsumerImpl.executeHookBefore(consumeMessageContext);
  17. }
  18. ...
  19. //调用应用程序消息监听器的consumeMessage方法,进入到具体的消息消费业务处理逻辑
  20. status = listener.consumeMessage(Collections.unmodifiableList(msgs), context);
  21. //执行消息处理后的钩子函数
  22. if (ConsumeMessageConcurrentlyService.this.defaultMQPushConsumerImpl.hasHook()) {
  23. consumeMessageContext.setStatus(status.toString());
  24. consumeMessageContext.setSuccess(ConsumeConcurrentlyStatus.CONSUME_SUCCESS == status);
  25. ConsumeMessageConcurrentlyService.this.defaultMQPushConsumerImpl.executeHookAfter(consumeMessageContext);
  26. }

2.5.7 定时消息机制

定时消息是消息发送到Broker后,并不立即被消费者消费而是要等到特定的时间后才能被消费,RocketMQ并不支持任意的时间精度,如果要支持任意时间精度定时调度,不可避免地需要在Broker层做消息排序,再加上持久化方面的考量,将不可避免的带来巨大的性能消耗,所以RocketMQ只支持特定级别的延迟消息。消息延迟级别在Broker端通过messageDelayLevel配置,默认为“1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h”,delayLevel=1表示延迟消息1s,delayLevel=2表示延迟5s,依次类推。
RocketMQ定时消息实现类为ScheduleMessageService,该类在DefaultMessageStore中创建。通过在DefaultMessageStore中调用load方法加载该类并调用start方法启动。
代码:ScheduleMessageService#load

  1. //加载延迟消息消费进度的加载与delayLevelTable的构造。延迟消息的进度默认存储路径为/store/config/delayOffset.json
  2. public boolean load() {
  3. boolean result = super.load();
  4. result = result && this.parseDelayLevel();
  5. return result;
  6. }

代码:ScheduleMessageService#start

  1. //遍历延迟队列创建定时任务,遍历延迟级别,根据延迟级别level从offsetTable中获取消费队列的消费进度。如果不存在,则使用0
  2. for (Map.Entry<Integer, Long> entry : this.delayLevelTable.entrySet()) {
  3. Integer level = entry.getKey();
  4. Long timeDelay = entry.getValue();
  5. Long offset = this.offsetTable.get(level);
  6. if (null == offset) {
  7. offset = 0L;
  8. }
  9. if (timeDelay != null) {
  10. this.timer.schedule(new DeliverDelayedMessageTimerTask(level, offset), FIRST_DELAY_TIME);
  11. }
  12. }
  13. //每隔10s持久化一次延迟队列的消息消费进度
  14. this.timer.scheduleAtFixedRate(new TimerTask() {
  15. @Override
  16. public void run() {
  17. try {
  18. if (started.get()) ScheduleMessageService.this.persist();
  19. } catch (Throwable e) {
  20. log.error("scheduleAtFixedRate flush exception", e);
  21. }
  22. }
  23. }, 10000, this.defaultMessageStore.getMessageStoreConfig().getFlushDelayOffsetInterval());

调度机制
ScheduleMessageService的start方法启动后,会为每一个延迟级别创建一个调度任务,每一个延迟级别对应SCHEDULETOPIC_XXXX主题下的一个消息消费队列。定时调度任务的实现类为DeliverDelayedMessageTimerTask,核心实现方法为executeOnTimeup
**
代码:ScheduleMessageService$DeliverDelayedMessageTimerTask#executeOnTimeup_**

  1. //根据队列ID与延迟主题查找消息消费队列
  2. ConsumeQueue cq =
  3. ScheduleMessageService.this.defaultMessageStore.findConsumeQueue(SCHEDULE_TOPIC,
  4. delayLevel2QueueId(delayLevel));
  5. ...
  6. //根据偏移量从消息消费队列中获取当前队列中所有有效的消息
  7. SelectMappedBufferResult bufferCQ = cq.getIndexBuffer(this.offset);
  8. ...
  9. //遍历ConsumeQueue,解析消息队列中消息
  10. for (; i < bufferCQ.getSize(); i += ConsumeQueue.CQ_STORE_UNIT_SIZE) {
  11. long offsetPy = bufferCQ.getByteBuffer().getLong();
  12. int sizePy = bufferCQ.getByteBuffer().getInt();
  13. long tagsCode = bufferCQ.getByteBuffer().getLong();
  14. if (cq.isExtAddr(tagsCode)) {
  15. if (cq.getExt(tagsCode, cqExtUnit)) {
  16. tagsCode = cqExtUnit.getTagsCode();
  17. } else {
  18. //can't find ext content.So re compute tags code.
  19. log.error("[BUG] can't find consume queue extend file content!addr={}, offsetPy={}, sizePy={}",
  20. tagsCode, offsetPy, sizePy);
  21. long msgStoreTime = defaultMessageStore.getCommitLog().pickupStoreTimestamp(offsetPy, sizePy);
  22. tagsCode = computeDeliverTimestamp(delayLevel, msgStoreTime);
  23. }
  24. }
  25. long now = System.currentTimeMillis();
  26. long deliverTimestamp = this.correctDeliverTimestamp(now, tagsCode);
  27. ...
  28. //根据消息偏移量与消息大小,从CommitLog中查找消息.
  29. MessageExt msgExt =
  30. ScheduleMessageService.this.defaultMessageStore.lookMessageByOffset(
  31. offsetPy, sizePy);
  32. }

2.5.8 顺序消息

顺序消息实现类是org.apache.rocketmq.client.impl.consumer.ConsumeMessageOrderlyService
代码:ConsumeMessageOrderlyService#start

  1. public void start() {
  2. //如果消息模式为集群模式,启动定时任务,默认每隔20s执行一次锁定分配给自己的消息消费队列
  3. if (MessageModel.CLUSTERING.equals(ConsumeMessageOrderlyService.this.defaultMQPushConsumerImpl.messageModel())) {
  4. this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
  5. @Override
  6. public void run() {
  7. ConsumeMessageOrderlyService.this.lockMQPeriodically();
  8. }
  9. }, 1000 * 1, ProcessQueue.REBALANCE_LOCK_INTERVAL, TimeUnit.MILLISECONDS);
  10. }
  11. }

代码:ConsumeMessageOrderlyService#submitConsumeRequest

  1. //构建消息任务,并提交消费线程池中
  2. public void submitConsumeRequest(
  3. final List<MessageExt> msgs,
  4. final ProcessQueue processQueue,
  5. final MessageQueue messageQueue,
  6. final boolean dispathToConsume) {
  7. if (dispathToConsume) {
  8. ConsumeRequest consumeRequest = new ConsumeRequest(processQueue, messageQueue);
  9. this.consumeExecutor.submit(consumeRequest);
  10. }
  11. }

代码:ConsumeMessageOrderlyService$ConsumeRequest#run

  1. //如果消息队列为丢弃,则停止本次消费任务
  2. if (this.processQueue.isDropped()) {
  3. log.warn("run, the message queue not be able to consume, because it's dropped. {}", this.messageQueue);
  4. return;
  5. }
  6. //从消息队列中获取一个对象。然后消费消息时先申请独占objLock锁。顺序消息一个消息消费队列同一时刻只会被一个消费线程池处理
  7. final Object objLock = messageQueueLock.fetchLockObject(this.messageQueue);
  8. synchronized (objLock) {
  9. ...
  10. }

2.5.9 小结

RocketMQ消息消费方式分别为集群模式、广播模式。
消息队列负载由RebalanceService线程默认每隔20s进行一次消息队列负载,根据当前消费者组内消费者个数与主题队列数量按照某一种负载算法进行队列分配,分配原则为同一个消费者可以分配多个消息消费队列,同一个消息消费队列同一个时间只会分配给一个消费者。
消息拉取由PullMessageService线程根据RebalanceService线程创建的拉取任务进行拉取,默认每次拉取32条消息,提交给消费者消费线程后继续下一次消息拉取。如果消息消费过慢产生消息堆积会触发消息消费拉取流控。
并发消息消费指消费线程池中的线程可以并发对同一个消息队列的消息进行消费,消费成功后,取出消息队列中最小的消息偏移量作为消息消费进度偏移量存储在于消息消费进度存储文件中,集群模式消息消费进度存储在Broker(消息服务器),广播模式消息消费进度存储在消费者端。
RocketMQ不支持任意精度的定时调度消息,只支持自定义的消息延迟级别,例如1s、2s、5s等,可通过在broker配置文件中设置messageDelayLevel。
顺序消息一般使用集群模式,是指对消息消费者内的线程池中的线程对消息消费队列只能串行消费。并并发消息消费最本质的区别是消息消费时必须成功锁定消息消费队列,在Broker端会存储消息消费队列的锁占用情况。