RocketMQ—消息偏移量总结

1 客户端逻辑
1.1 概述
偏移量管理主要是指管理每个消息队列的消费进度:集群模式消费下会将消息队列的消费进度保存在Broker端,广播模式消费下消息队列的消费进度保存在消费者本地。
组件分析:RocketMQ定义了一个接口OffsetStore。它的实现类有两个:RemoteBrokerOffsetStore和LocalFileOffsetStore前者主要是集群消费模式下使用,即与broker进行打交道,将消息队列的消费偏移量通过网络传递给Broker;后者主要是广播消费模式下使用,即直接将消费偏移量存储在消费者所在的本地中。入下图所示:

offsetstore保存在消费者内部客户端ConsumerInner的实现类中的,其初始化创建的时机在内部客户端的start()方法中。offsetstore保存在消费者内部客户端ConsumerInner的实现类中的,其初始化创建的时机在内部客户端的start()方法中。

 1                 if (this.defaultMQPullConsumer.getOffsetStore() != null) {
 2                     this.offsetStore = this.defaultMQPullConsumer.getOffsetStore();
 3                 } else {
 4                     switch (this.defaultMQPullConsumer.getMessageModel()) {
 5                         case BROADCASTING:
 6                             this.offsetStore = new LocalFileOffsetStore(this.mQClientFactory, this.defaultMQPullConsumer.getConsumerGroup());
 7                             break;
 8                         case CLUSTERING:
 9                             this.offsetStore = new RemoteBrokerOffsetStore(this.mQClientFactory, this.defaultMQPullConsumer.getConsumerGroup());
10                             break;
11                         default:
12                             break;
13                     }
14                     this.defaultMQPullConsumer.setOffsetStore(this.offsetStore);
15                 }

下面主要分析RemoteBrokerOffsetStore的逻辑。
主要是两个逻辑,如下图所示

  • 将消息偏移量更新到本地内存中管理消息偏移量的组件
  • 将内存中保存的消息偏移量发送给Broker,更新Broker端保存的消息偏移量

1.2 更新消息队列的偏移量
并发消息消费服务中ConsumeMessageConcurrentlyService#processConsumeResult()处理消息消费结果的方法中在消息处理完成以后会调用更新消息队列的偏移量

1 // 获取偏移量存储实现,并调用其更新偏移量方法更新偏移量  
2       long offset = consumeRequest.getProcessQueue().removeMessage(consumeRequest.getMsgs());
3         if (offset >= 0 && !consumeRequest.getProcessQueue().isDropped()) {
4             this.defaultMQPushConsumerImpl.getOffsetStore().updateOffset(consumeRequest.getMessageQueue(), offset, true);
5         }

下面是RemoteBrokerOffsetStore的更新逻辑
将已经确认消费了的偏移量存储偏移量管理器中。此处的更新仅仅是更新了保存每个消息队列的偏移量的map中的值,并没有将偏移量上传到broker。

 1 public void updateOffset(MessageQueue mq, long offset, boolean increaseOnly) {
 2     if (mq != null) {
 3         // ConcurrentMap<MessageQueue, AtomicLong>
 4         // 获取消息队列对应的偏移量
 5         AtomicLong offsetOld = this.offsetTable.get(mq);
 6         if (null == offsetOld) {
 7             // 更新table
 8             offsetOld = this.offsetTable.putIfAbsent(mq, new AtomicLong(offset));
 9         }
10 
11         if (null != offsetOld) {
12             // 是否是只增模式
13             if (increaseOnly) {
14                 MixAll.compareAndIncreaseOnly(offsetOld, offset);
15             } else {
16                 offsetOld.set(offset);
17             }
18         }
19     }
20 }

1.3 向Broker发送消息偏移量
向服务端发送消息偏移量是通过MQClientInstance中启动的一个定时任务来完成的。
1 在其startScheduledTask方法中开启下列定时任务

this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() {

    @Override
    public void run() {
        try {
            // 对已消费的消息的偏移量进行持久化
            MQClientInstance.this.persistAllConsumerOffset();
        } catch (Exception e) {
            log.error("ScheduledTask persistAllConsumerOffset exception", e);
        }
    }
}, 1000 * 10, this.clientConfig.getPersistConsumerOffsetInterval(), TimeUnit.MILLISECONDS);

2 调用MQClientInstance的persisAllConsumerOffset()方法

private void persistAllConsumerOffset() {
    // 获取所有消费者组对应的内部客户端
    Iterator<Entry<String, MQConsumerInner>> it = this.consumerTable.entrySet().iterator();
    while (it.hasNext()) {
        Entry<String, MQConsumerInner> entry = it.next();
        MQConsumerInner impl = entry.getValue();
        // 调用内部客户端进行持久化
        impl.persistConsumerOffset();
    }
}

3 调用内部消费者客户端的持久化方法

public void persistConsumerOffset() {
    try {
        this.makeSureStateOK();
        Set<MessageQueue> mqs = new HashSet<MessageQueue>();
        // 获取所有的分配的消息队列
        Set<MessageQueue> allocateMq = this.rebalanceImpl.getProcessQueueTable().keySet();
        mqs.addAll(allocateMq);
        // 持久化偏移量
        this.offsetStore.persistAll(mqs);
    } catch (Exception e) {
        log.error("group: " + this.defaultMQPushConsumer.getConsumerGroup() + " persistConsumerOffset exception", e);
    }
}

4 调用偏移量管理器的更新

 1 public void persistAll(Set<MessageQueue> mqs) {
 2     if (null == mqs || mqs.isEmpty())
 3         return;
 4 
 5     final HashSet<MessageQueue> unusedMQ = new HashSet<MessageQueue>();
 6 
 7     // 遍历保存消息队列偏移量的map
 8     for (Map.Entry<MessageQueue, AtomicLong> entry : this.offsetTable.entrySet()) {
 9         MessageQueue mq = entry.getKey();
10         AtomicLong offset = entry.getValue();
11         if (offset != null) {
12             if (mqs.contains(mq)) {
13                 try {
14                     // 更新到
15                     this.updateConsumeOffsetToBroker(mq, offset.get());
16                     log.info("[persistAll] Group: {} ClientId: {} updateConsumeOffsetToBroker {} {}",
17                             this.groupName,
18                             this.mQClientFactory.getClientId(),
19                             mq,
20                             offset.get());
21                 } catch (Exception e) {
22                     log.error("updateConsumeOffsetToBroker exception, " + mq.toString(), e);
23                 }
24             } else {
25                 unusedMQ.add(mq);
26             }
27         }
28     }
29 
30     if (!unusedMQ.isEmpty()) {
31         for (MessageQueue mq : unusedMQ) {
32             this.offsetTable.remove(mq);
33             log.info("remove unused mq, {}, {}", mq, this.groupName);
34         }
35     }
36 } 

接下来就是通过网络层发送网络请求给Broker进行更新消息对立偏移量。
1.4 读取消息队列的偏移量
两个时刻需要获取Broker保存的偏移量

  • 消费者刚启动的时候会去Broker获取消息队列对应的偏移量
  • 消费者重平衡后,分配得到新的消息队列,也要重新获取偏移量

readOffset
在DefaultMQPushConsumerImpl的pullMessage方法中,在消费之前会读取一次

 1 commitOffsetValue = this.offsetStore.readOffset(pullRequest.getMessageQueue(), ReadOffsetType.READ_FROM_MEMORY); 

2 服务端的处理逻辑
服务端注册了的消费消息偏移量的请求处理器,首先是有关偏移量的三个请求码
GET_CONSUMER_LIST_BY_GROUP:根据组名获取消费者列表
UPDATE_CONSUMER_OFFSET:更新消费偏移量的请求
QUERY_CONSUMER_OFFSET:查询消费者的偏移量
所以这三个的请求码将交给ConsumerManageProcessor来进行处理。

1       /**
2          * ConsumerManageProcessor
3          */
4         ConsumerManageProcessor consumerManageProcessor = new ConsumerManageProcessor(this);
5         this.remotingServer.registerProcessor(RequestCode.GET_CONSUMER_LIST_BY_GROUP, consumerManageProcessor, this.consumerManageExecutor);
6         this.remotingServer.registerProcessor(RequestCode.UPDATE_CONSUMER_OFFSET, consumerManageProcessor, this.consumerManageExecutor);
7         this.remotingServer.registerProcessor(RequestCode.QUERY_CONSUMER_OFFSET, consumerManageProcessor, this.consumerManageExecutor);

2.1 更新消费者传给broker的消费偏移量

内存存储方式
位置:ConsumerOffsetManager的offsetTable中
格式:ConcurrentMap<String/* topic@group */, ConcurrentMap<Integer, Long>>,第一层key是主题+消费者组,集群模式下的消费模式;第二层的key是QueueID队列ID。
外部存储位置:

2.2 源码分析
2.2.1 处理偏移量更新请求和更新到内存中的流程
1 请求处理的入口

 1 // RocketMQ里面的通用做法,发送请求时将给请求赋值一个请求码;
 2 // 服务端在接收到请求的时候将根据请求码选择不同的请求处理处理器;
 3 // 统一的接口processRequest()
 4 public RemotingCommand processRequest(ChannelHandlerContext ctx, RemotingCommand request)
 5         throws RemotingCommandException {
 6     // ConsuemrManagerProcessor内部又分了不同的处理逻辑
 7     switch (request.getCode()) {
 8         // 处理
 9         case RequestCode.GET_CONSUMER_LIST_BY_GROUP:
10             return this.getConsumerListByGroup(ctx, request);
11         // 处理更新偏移量
12         case RequestCode.UPDATE_CONSUMER_OFFSET:
13             return this.updateConsumerOffset(ctx, request);
14         case RequestCode.QUERY_CONSUMER_OFFSET:
15             return this.queryConsumerOffset(ctx, request);
16         default:
17             break;
18     }
19     return null;
20 }

2 处理更新消费偏移量的入口

 1 private RemotingCommand updateConsumerOffset(ChannelHandlerContext ctx, RemotingCommand request)
 2         throws RemotingCommandException {
 3     // 首先创建响应,RocketMQ中惯例做法,具体可参照
 4     final RemotingCommand response =
 5             RemotingCommand.createResponseCommand(UpdateConsumerOffsetResponseHeader.class);
 6     // 解码请求头
 7     final UpdateConsumerOffsetRequestHeader requestHeader =
 8             (UpdateConsumerOffsetRequestHeader) request
 9                     .decodeCommandCustomHeader(UpdateConsumerOffsetRequestHeader.class);
10     // 调用消费偏移量偏移器进行更新消费偏移量
11     this.brokerController.getConsumerOffsetManager()
12             .commitOffset(
13                     RemotingHelper.parseChannelRemoteAddr(ctx.channel()),
14                     requestHeader.getConsumerGroup(), // 消费者组
15                     requestHeader.getTopic(), // 主题
16                     requestHeader.getQueueId(), // 队列ID
17                     requestHeader.getCommitOffset()); // 偏移量
18     response.setCode(ResponseCode.SUCCESS);
19     response.setRemark(null);
20     return response;
21 }

3 消费偏移量管理器更新偏移量的入口

1 public void commitOffset(final String clientHost, final String group, final String topic, final int queueId,
2     final long offset) {
3     // topic@group
4     // 构建key: 主题/消费者组名
5     String key = topic + TOPIC_GROUP_SEPARATOR + group;
6     this.commitOffset(clientHost, key, queueId, offset);
7 }

4 将消费者端传上来的消费偏移量存储到内存之中的map

 1 private void commitOffset(final String clientHost, final String key, final int queueId, final long offset) {
 2     // 使用 主题/消费者名 获取存储偏移量的map<queueId, offset>
 3     ConcurrentMap<Integer, Long> map = this.offsetTable.get(key);
 4     if (null == map) {
 5         map = new ConcurrentHashMap<Integer, Long>(32);
 6         map.put(queueId, offset);
 7         this.offsetTable.put(key, map);
 8     } else {
 9         Long storeOffset = map.put(queueId, offset);
10         if (storeOffset != null && offset < storeOffset) {
11             log.warn("[NOTIFYME]update consumer offset less than store. clientHost={}, key={}, queueId={}, requestOffset={}, storeOffset={}", clientHost, key, queueId, offset, storeOffset);
12         }
13     }
14 }

2.2.2 消息偏移量持久化到磁盘
1、启动定时任务,该定时任务在BrokerController中被启动的;

 1 this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
 2     @Override
 3     public void run() {
 4         try {
 5             // 持久化偏移量
 6             BrokerController.this.consumerOffsetManager.persist();
 7         } catch (Throwable e) {
 8             log.error("schedule persist consumerOffset error.", e);
 9         }
10     }
11 }, 1000 * 10, this.brokerConfig.getFlushConsumerOffsetInterval(), TimeUnit.MILLISECONDS);

2、调用ConsuemerOffsetManager进行偏移量持久化

 1 public synchronized void persist() {
 2     // 先进行编码
 3     String jsonString = this.encode(true);
 4     if (jsonString != null) {
 5         // 获取存储文件的路径
 6         String fileName = this.configFilePath();
 7         try {
 8             // 将存储内容存到磁盘
 9             MixAll.string2File(jsonString, fileName);
10         } catch (IOException e) {
11             log.error("persist file " + fileName + " exception", e);
12         }
13     }
14 }
郭慕荣博客园
原文地址:https://www.cnblogs.com/jelly12345/p/14463071.html