LocalMQ:从零构建类 RocketMQ 高性能消息队列

开发 开发工具
本文记录了月前笔者参与阿里云中间件比赛中,实现的简要具有持久化功能的消息队列的设计与实现过程。需要声明的是,LocalMQ 借鉴了 RocketMQ 在 Broker 部分的核心设计思想,最早的源码也是基于 RocketMQ 源码改造而来。

[[196547]]

本文记录了月前笔者参与阿里云中间件比赛中,实现的简要具有持久化功能的消息队列的设计与实现过程。需要声明的是,LocalMQ 借鉴了 RocketMQ 在 Broker 部分的核心设计思想,最早的源码也是基于 RocketMQ 源码改造而来。本文涉及引用以及其他消息队列相关资料参考这里,源代码放于 LocalMQ 仓库;另外笔者水平有限,后来因为毕业旅行也未继续优化,本文很多内容可能存在谬误与不足,请批评指正。

LocalMQ:从零构建类 RocketMQ 高性能消息队列

所谓消息队列,直观来看有点像蓄水池,能够在生产者与消费者之间完成解耦,并且平衡生产者与消费者之间的计算量与可计算时间之间的差异;目前主流的消息队列有著名的 Kafka、RabbitMQ、RocketMQ 等等。在笔者实现的 LocalMQ 中,从简到复依次实现了 MemoryMessageMQ、EmbeddedMessageQueue 与 LocalMessageQueue 这三个版本;需要说明的是,在三个版本的消息队列中,都是采取所谓的拉模式,即消费者主动向消息队列请求拉取消息的模式。在 wx.demo.* 包下提供了很多的内部功能与性能测试用例,

  1. // 首先在这里:https://parg.co/beX 下载代码 
  2. // 然后修改 DefaultProducer 对应的继承类 
  3. // 测试 MemoryMessageQueue,则继承 MemoryProducer; 
  4. // 测试 EmbeddedMessageQueue,则继承 EmbeddedProducer; 
  5. // 默认测试 LocalMessageQueue,注意,需要对 DefaultPullConsumer 进行同样修改 
  6. public class DefaultProducer extends LocalProducer 
  7.  
  8. // 使用 mvn 运行测试用例,也可以在 Eclipse 或者 Intellij 中打开 
  9. mvn clean package -U assembly:assembly -Dmaven.test.skip=true 
  10.  
  11. java -Xmx2048m -Xms2048m  -cp open-messaging-wx.demo-1.0.jar  wx.demo.benchmark.ProducerBenchmark 

最简单的 MemoryMessageQueue 即是将消息数据按照选定主题存放在内存中,其主要结构如下图所示:

MemoryMessageQueue 提供了同步的消息提交与拉取操作,其利用 HashMap 堆上存储来缓存所有的消息;并且在内存中维护了另一个所谓的 QueueOffsets 来记录每个主题对应队列的消费偏移量。相较于 MemoryMessageQueue 实现的简单的不能进行持久化存储的消息队列,EmbeddedMessageQueue 则提供了稍微复杂点的支持磁盘持久化的消息队列。EmbeddedMessageQueue 构建了基于 Java NIO 提供的 MappedByteBuffer 的 MappedPartitionQueue。每个 MappedPartitionQueue 对应磁盘上的多个物理文件,并且为上层应用抽象提供了逻辑上的单一文件。EmbeddedMessageQueue 结构如下图所示:


 

EmbeddedMessageQueue 的主要流程为生产者同步地像 Bucket Queue 中提交消息,每个 Bucket 可以视作某个主题(Topic)或者队列(Queue)。而 EmbeddedMessageQueue 还包含着负责定期将 MappedPartitionQueue 中数据持久化写入到磁盘的异步线程,该线程会定期地完成 Flush 操作。EmbeddedMessageQueue 假设某个 BucketQueue 被分配给某个 Consumer 之后就被其占用,该 Consumer 会消费其中全部的缓存消息;每个 Consumer 会包含独立地 Consumer Offset Table 来记录当前某个队列地消费情况。EmbeddedMessageQueue 的缺陷在于:

  • 混合处理与标记位:EmbeddedMessageQueue 仅提供了最简单的消息序列化模型,无法记录额外的消息属性;
  • 持久化存储到磁盘的时机:EmbeddedMessageQueue 仅使用了一级缓存,并且仅在某个 Partition 写满时才进行文件的持久化操作;
  • 添加消息的后处理:EmbeddedMessageQueue 是将消息直接写入到 BucketQueue 包含的 MappedPartitionQueue 中,无法动态地进行索引、筛选等消息后处理,其可扩展性较差。
  • 未考虑断续拉取的情况:EmbeddedMessageQueue 中是假设 Consumer 能够单次处理完某个 BucketQueue 中的单个 Partition 的全部消息,因此记录其处理值时也仅是记录了文件级别的位移,如果存在某次是仅拉取了单个 Partition 中部分内容,则下次的起始拉取点还是下个文件首。

EmbeddedMessageQueue 中我们可以在各 Producer 线程中单独将消息持久化入文件中,而在 LocalMessageQueue 中,我们是将消息统一写入 MessageStore 中,然后又 PostPutMessageService 进行二次处理。 LocalMessageQueue 的结构如下所示:

LocalMessageQueue 最大的变化在于将消息统一存储在独立地 MessageStore 中(类似于 RocketMQ 中的 CommitLog),然后针对 Topic-queueId 将消息划分到不同的 ConsumeQueue 中;这里的 queueId 是由对应的 Producer 专属编号决定的,每个 Consumer 即会被分配占用某个 ConsumeQueue(类似于 RocketMQ 中的 consumequeue),从而保证某个 Producer 生产的某个主题下的消息被专一的 Consumer 消费。LocalMessageQueue 同样使用 MappedPartitionQueue 提供底层文件系统抽象,并且构建了独立的 ConsumerOffsetManager 对消费者的消费进度进行管理,从而方便异常恢复。

设计概要

顺序消费

消息产品的一个重要特性是顺序保证,也就是消息消费的顺序要与发送的时间顺序保持一致;在多发送端的情况下,保证全局顺序代价比较大,只要求各个发送端的顺序有保障即可; 举个例子 P1 发送 M11, M12, M13,P2 发送 M21, M22, M23,在消费的时候,只要求保证 M11, M12, M13(M21,M22,M23)的顺序,也就是说,实际消费顺序为: M11, M21, M12, M13, M22, M23 正确; M11, M21, M22, M12, M13, M23 正确 M11, M13, M21, M22, M23, M12 错误,M12 与 M13 的顺序颠倒了;假如生产者产生了 2 条消息:M1、M2,要保证这两条消息的顺序,最直观的方式就是采取类似于 TCP 中的确认消息:

不过该模型中如果 M1 与 M2 分别被发送到了两台不同的消息服务器上,我们无法控制消息服务器发送 M1 与 M2 的先后时机;有可能 M2 已经被发送到了消费者,M1 才被发送到了消息服务器上。针对这个问题改进版的思路即是将 M1 与 M2 发送到单一消息服务器中,然后根据先到达先消费的原则发送给对应的消费者:

 

不过在实际情况下往往因为网络延迟或其他问题导致在 M1 发送耗时大于 M2 的情况下,M2 会先于 M1 被消费。因此如果我们要保证严格的顺序消息,那么必须要保证生产者、消息服务器与消费者之间的一对一对应关系。在 LocalMQ 的实现中,我们首先会将消息按照生产者划分到唯一的 Topic-queueId 队列中;并且保证同一时刻该消费队列只会被某个消费者独占。如果某个消费者在消费完该队列之前意外中断,那么在保留窗口期内不会将该队列重新分配;在窗口期之外则将该队列分配给新的消费者,并且即使原有消费者恢复工作也无法继续拉取该队列中包含的消息。

数据存储

LocalMQ 中目前是实现了基于文件系统的持久化存储,主要功能实现在 MappedPartition 与 MappedPartitionQueue 这两个类中,笔者也会在下文中详细介绍这两个类的实现。本部分我们讨论下数据存储的文件格式,对于 LocalMessageQueue 而言,其文件存储如下:

  1. * messageStore 
  2. -- MapFile1 
  3. -- MapFile2 
  4. * consumeQueue 
  5. -- Topic1 
  6. ---- queueId1 
  7. ------ MapFile1 
  8. ------ MapFile2 
  9. ---- queueId2 
  10. ------ MapFile1 
  11. ------ MapFile2 
  12. -- Queue1 
  13. ---- queueId1 
  14. ------ MapFile1 
  15. ------ MapFile2 
  16. ---- queueId2 
  17. ------ MapFile1 
  18. ------ MapFile2 

LocalMessageQueue 中采用了消息统一存储的方案,因此所有的消息实际内容会被存放在 messageStore 目录下。而 consumeQueue 中则存放了消息的索引,即在 messageStore 中的偏移地址。LocalMQ 中使用 MappedPartitionQueue 来管理某个逻辑上单一的文件,而根据不同的单文件大小限制会自动将其切割为多个物理上独立的 Mapped File。每个 MappedPartition 使用 offset,即该文件首地址的全局偏移量命名;而使用 pos / position 统一表示单文件中局部偏移量,使用 index 表示某个文件在其文件夹中的下标。

性能优化

在编写的过程中,笔者发现对于执行流的优化、避免重复计算与额外变量、选择使用合适的并发策略都会对结果造成极大的影响,譬如笔者从 SpinLock 切换到重入锁之后,本地测试 TPS 增加了约 5%。另外笔者也统计了消费者工作中不同阶段的时间占比,其中构建(包括消息属性的序列化)与发送操作(写入到 MappedFileQueue 中,未使用二级缓存)都是同步进行,二者的时间占比也是最多。

  1. [2017-06-01 12:13:21,802] INFO: 构建耗时占比:0.471270,发送耗时占比:0.428567,持久化耗时占比:0.100163 
  2. [2017-06-01 12:25:31,275] INFO: 构建耗时占比:0.275170,发送耗时占比:0.573520,持久化耗时占比:0.151309 

代码级别优化

笔者在实现 LocalMQ 的过程中感触最深的就是实现相同功能的不同代码在性能上的差异可能会很大。在实现过程中应该避免冗余变量声明与创建、避免额外空间申请与垃圾回收、避免冗余的执行过程;另外尽可能选用合适的数据结构,譬如笔者在部分实现中从 ArrayList 迁移到了 LinkedList,从 ConcurrentHashMap 迁移到了 HashMap,都带来了一定的评测指标提升。

异步 IO

异步 IO,顺序 Flush;笔者发现,如果多个线程进行并发 Flush 操作,反而不如单线程进行顺序 Flush。

并发控制

  • 尽量减少锁控制的范围。
  • 并发计算优化,将所有的耗时计算放到可以并发的 Producer 中。
  • 使用合理的锁,重入锁相较于自旋锁有近 5 倍的 TPS 提升。

MemoryMessageQueue

源代码参考这里MemoryMessageQueue 是最简易的实现,不过其代码能够反映出某个消息队列的基本流程,首先在生产者我们需要创建消息并且发送给消息队列:

  1. // 创建消息 
  2. BytesMessage message = messageFactory.createBytesMessageToTopic(topic, body); 
  3.  
  4. // 发送消息 
  5. messageQueue.putMessage(topic, message); 

在 putMessage 函数中则将消息存入内存存储中:

  1. // 存放所有消息 
  2. private Map<String, ArrayList<Message>> messageBuckets = new HashMap<>(); 
  3.  
  4. // 添加消息 
  5. public synchronized PutMessageResult putMessage(String bucket, Message message) { 
  6.         if (!messageBuckets.containsKey(bucket)) { 
  7.             messageBuckets.put(bucket, new ArrayList<>(1024)); 
  8.         } 
  9.         ArrayList<Message> bucketList = messageBuckets.get(bucket); 
  10.         bucketList.add(message); 
  11.  
  12.         return new PutMessageResult(PutMessageStatus.PUT_OK, null); 
  13.     } 

而 Consumer 则根据指定的 Bucket 与 queueId 来拉取消息,如果存在多个 Bucket 需要拉取则进行轮询:

  1. //use Round Robin 
  2. int checkNum = 0; 
  3.  
  4. while (++checkNum <= bucketList.size()) { 
  5.     String bucket = bucketList.get((++lastIndex) % (bucketList.size())); 
  6.     Message message = messageQueue.pullMessage(queue, bucket); 
  7.     if (message != null) { 
  8.         return message; 
  9.     } 

而 MemoryMessageQueue 的 pullMessage 函数则首先判断目标 Bucket 是否存在,并且根据内置的 queueOffset 中记录的拉取偏移量来判断是否拉取完毕。若没有拉取完毕则返回消息并且更新本地偏移量;

  1. private Map<String, HashMap<String, Integer>> queueOffsets = new HashMap<>(); 
  2. ... 
  3. public synchronized Message pullMessage(String queue, String bucket) { 
  4.     ... 
  5.     ArrayList<Message> bucketList = messageBuckets.get(bucket); 
  6.     if (bucketList == null) { 
  7.         return null
  8.     } 
  9.     HashMap<String, Integer> offsetMap = queueOffsets.get(queue); 
  10.     if (offsetMap == null) { 
  11.         offsetMap = new HashMap<>(); 
  12.         queueOffsets.put(queue, offsetMap); 
  13.     } 
  14.     int offset = offsetMap.getOrDefault(bucket, 0); 
  15.     if (offset >= bucketList.size()) { 
  16.         return null
  17.     } 
  18.     Message message = bucketList.get(offset); 
  19.     offsetMap.put(bucket, ++offset); 
  20.     ... 

EmbeddedMessageQueue

源代码参考这里

EmbeddedMessageQueue 中引入了消息持久化支持,本部分我们也主要讨论消息序列化与底层的 MappedPartitionQueue 实现。

消息序列化

EmbeddedMessageQueue 中定义的消息格式如下:

序号消息存储结构备注长度(字节数)1TOTALSIZE消息大小42MAGICCODE消息的 MAGIC CODE43BODY前 4 个字节存放消息体大小值,后 bodyLength 大小的空间存储消息体内容4 + bodyLength4headers*前 2 个字节(short)存放头部大小,后存放 headersLength 大小的头部数据2 + headersLength5properties*前 2 个字节(short)存放属性值大小,后存放 propertiesLength 大小的属性数据2 + propertiesLength

  1. /** 
  2.     * Description 计算某个消息的长度,注意,headersByteArray 与 propertiesByteArray 在发送消息时完成转换 
  3.     * @param message 
  4.     * @param headersByteArray 
  5.     * @param propertiesByteArray 
  6.     * @return 
  7.     */ 
  8. public static int calMsgLength(DefaultBytesMessage message, byte[] headersByteArray, byte[] propertiesByteArray) { 
  9.  
  10.     // 消息体 
  11.     byte[] body = message.getBody(); 
  12.  
  13.     int bodyLength = body == null ? 0 : body.length; 
  14.  
  15.     // 计算头部长度 
  16.     short headersLength = (short) headersByteArray.length; 
  17.  
  18.     // 计算属性长度 
  19.     short propertiesLength = (short) propertiesByteArray.length; 
  20.  
  21.     // 计算消息体总长度 
  22.     return calMsgLength(bodyLength, headersLength, propertiesLength); 
  23.  

而 EmbeddedMessageEncoder 的 encode 函数负责具体的消息序列化操作:

  1. /** 
  2.     * Description 执行消息的编码操作 
  3.     * @param message 消息对象 
  4.     * @param msgStoreItemMemory 内部缓存句柄 
  5.     * @param msgLen 计算的消息长度 
  6.     * @param headersByteArray 消息头字节序列 
  7.     * @param propertiesByteArray 消息属性字节序列 
  8. */ 
  9. public static final void encode( 
  10.     DefaultBytesMessage message, 
  11.     final ByteBuffer msgStoreItemMemory, 
  12.     int msgLen, 
  13.     byte[] headersByteArray, 
  14.     byte[] propertiesByteArray 
  15. ) { 
  16.  
  17. // 消息体 
  18. byte[] body = message.getBody(); 
  19.  
  20. int bodyLength = body == null ? 0 : body.length; 
  21.  
  22. // 计算头部长度 
  23. short headersLength = (short) headersByteArray.length; 
  24.  
  25. // 计算属性长度 
  26. short propertiesLength = (short) propertiesByteArray.length; 
  27.  
  28. // 初始化存储空间 
  29. resetByteBuffer(msgStoreItemMemory, msgLen); 
  30.  
  31. // 1 TOTALSIZE 
  32. msgStoreItemMemory.putInt(msgLen); 
  33.  
  34. // 2 MAGICCODE 
  35. msgStoreItemMemory.putInt(MESSAGE_MAGIC_CODE); 
  36.  
  37. // 3 BODY 
  38. msgStoreItemMemory.putInt(bodyLength); 
  39. if (bodyLength > 0) 
  40.     msgStoreItemMemory.put(message.getBody()); 
  41.  
  42. // 4 HEADERS 
  43. msgStoreItemMemory.putShort((short) headersLength); 
  44. if (headersLength > 0) 
  45.     msgStoreItemMemory.put(headersByteArray); 
  46.  
  47. // 5 PROPERTIES 
  48. msgStoreItemMemory.putShort((short) propertiesLength); 
  49. if (propertiesLength > 0) 
  50.     msgStoreItemMemory.put(propertiesByteArray); 
  51.  

对应的反序列化操作则是由 EmbeddedMessageDecoder 完成,其主要从某个 ByteBuffer 中读取数据:

  1. /** 
  2.     * Description 从输入的 ByteBuffer 中反序列化消息对象 
  3.     * 
  4.     * @return 0 Come the end of the file // >0 Normal messages // -1 Message checksum failure 
  5.     */ 
  6. public static DefaultBytesMessage readMessageFromByteBuffer(ByteBuffer byteBuffer) { 
  7.  
  8.     // 1 TOTAL SIZE 
  9.     int totalSize = byteBuffer.getInt(); 
  10.  
  11.     // 2 MAGIC CODE 
  12.     int magicCode = byteBuffer.getInt(); 
  13.  
  14.     switch (magicCode) { 
  15.         case MESSAGE_MAGIC_CODE: 
  16.             break; 
  17.         case BLANK_MAGIC_CODE: 
  18.             return null
  19.         default
  20. //                log.warning("found a illegal magic code 0x" + Integer.toHexString(magicCode)); 
  21.             return null
  22.     } 
  23.  
  24.     byte[] bytesContent = new byte[totalSize]; 
  25.  
  26.     // 3 BODY 
  27.     int bodyLen = byteBuffer.getInt(); 
  28.     byte[] body = new byte[bodyLen]; 
  29.  
  30.     if (bodyLen > 0) { 
  31.         // 读取并且校验消息体内容 
  32.         byteBuffer.get(body, 0, bodyLen); 
  33.     } 
  34.  
  35.     // 4 HEADERS 
  36.     short headersLength = byteBuffer.getShort(); 
  37.     KeyValue headers = null
  38.     if (headersLength > 0) { 
  39.         byteBuffer.get(bytesContent, 0, headersLength); 
  40.         String headersStr = new String(bytesContent, 0, headersLength, EmbeddedMessageDecoder.CHARSET_UTF8); 
  41.         headers = string2KeyValue(headersStr); 
  42.  
  43.     } 
  44.  
  45.     // 5 PROPERTIES 
  46.  
  47.     // 获取 properties 尺寸 
  48.     short propertiesLength = byteBuffer.getShort(); 
  49.     KeyValue properties = null
  50.     if (propertiesLength > 0) { 
  51.         byteBuffer.get(bytesContent, 0, propertiesLength); 
  52.         String propertiesStr = new String(bytesContent, 0, propertiesLength, EmbeddedMessageDecoder.CHARSET_UTF8); 
  53.         properties = string2KeyValue(propertiesStr); 
  54.  
  55.     } 
  56.  
  57.     // 返回读取到的消息 
  58.     return new DefaultBytesMessage( 
  59.             totalSize, 
  60.             headers, 
  61.             properties, 
  62.             body 
  63.     ); 
  64.  
  65.  

消息写入

EmbeddedMessageQueue 中消息的写入实际上是由 BucketQueue 的 putMessage/putMessages 函数完成的,这里的某个 BucketQueue 就对应着 Topic-queueId 这个唯一的标识。这里以批量写入消息为例,首先我们从 BucketQueue 包含的 MappedPartitionQueue 中获取到最新可用的某个 MappedPartition:

  1. mappedPartition = this.mappedPartitionQueue.getLastMappedFileOrCreate(0); 

然后调用 MappedPartition 的 appendMessages 方法,该方法会在下文介绍;这里则是要讨论添加消息的几种结果对应的处理。如果添加成功,则直接返回成功;如果该 MappedPartition 剩余空间不足以写入消息队列中的某条消息,则需要调用 MappedPartitionQueue 创建新的 MappedPartition,并且重新计算待写入的消息序列:

  1. ... 
  2. // 调用对应的 MappedPartition 追加消息 
  3. // 注意,这里经过填充之后,会逆向地将消息在 MessageStore 中的偏移与 QueueOffset 中偏移添加进去 
  4. result = mappedPartition.appendMessages(messages, this.appendMessageCallback); 
  5.  
  6. // 根据追加结果进行不同的操作 
  7. switch (result.getStatus()) { 
  8.     case PUT_OK: 
  9.         break; 
  10.     case END_OF_FILE: 
  11.  
  12.         this.messageQueue.getFlushAndUnmapPartitionService().putPartition(mappedPartition); 
  13.  
  14.         // 如果已经到了文件最后,则创建新文件 
  15.         mappedPartition = this.mappedPartitionQueue.getLastMappedFileOrCreate(0); 
  16.  
  17.         if (null == mappedPartition) { 
  18.             // XXX: warn and notify me 
  19.             log.warning("创建 MappedPartition 错误, topic: " + messages.get(0).getTopicOrQueueName()); 
  20.             beginTimeInLock = 0; 
  21.             return new PutMessageResult(PutMessageStatus.CREATE_MAPEDFILE_FAILED, result); 
  22.         } 
  23.         // 否则重新进行添加操作 
  24.         // 从结果中获取处理完毕的消息数 
  25.         int appendedMessageNum = result.getAppendedMessageNum(); 
  26.  
  27.         // 创建临时的 LeftMessages 
  28.         ArrayList<DefaultBytesMessage> leftMessages = new ArrayList<>(); 
  29.  
  30.         // 添加所有未消费的消息 
  31.         for (int i = appendedMessageNum; i < messages.size(); i++) { 
  32.             leftMessages.add(messages.get(i)); 
  33.         } 
  34.  
  35.         result = mappedPartition.appendMessages(leftMessages, this.appendMessageCallback); 
  36.  
  37.         break; 
  38.     case MESSAGE_SIZE_EXCEEDED: 
  39.     case PROPERTIES_SIZE_EXCEEDED: 
  40.         beginTimeInLock = 0; 
  41.         return new PutMessageResult(PutMessageStatus.MESSAGE_ILLEGAL, result); 
  42.     case UNKNOWN_ERROR: 
  43.         beginTimeInLock = 0; 
  44.         return new PutMessageResult(PutMessageStatus.UNKNOWN_ERROR, result); 
  45.     default
  46.         beginTimeInLock = 0; 
  47.         return new PutMessageResult(PutMessageStatus.UNKNOWN_ERROR, result); 
  48. ... 

逻辑文件存储

Mapped Partition

某个 MappedPartition 映射物理上的单个文件,其初始化时如下传入文件名与文件尺寸属性:

  1. /** 
  2.     * Description 初始化某个内存映射文件 
  3.     * 
  4.     * @param fileName 文件名 
  5.     * @param fileSize 文件尺寸 
  6.     * @throws IOException 打开文件出现异常 
  7.     */ 
  8. private void init(final String fileName, final int fileSize) throws IOException { 
  9.     ... 
  10.  
  11.     // 从文件名中获取到当前文件的全局偏移量 
  12.     this.fileFromOffset = Long.parseLong(this.file.getName()); 
  13.  
  14.     ...  
  15.  
  16.     // 尝试打开文件 
  17.     this.fileChannel = new RandomAccessFile(this.file, "rw").getChannel(); 
  18.  
  19.     // 将文件映射到内存中 
  20.     this.mappedByteBuffer = this.fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, fileSize); 

初始化阶段即打开文件映射,而后在写入消息或者其他内容时,其会调用传入的消息编码回调(即是我们上文中介绍的消息序列化的包裹对象)将对象编码为字节流并且写入:

  1. public AppendMessageResult appendMessage(final DefaultBytesMessage message, final AppendMessageCallback cb) { 
  2.  
  3.     ... 
  4.  
  5.     // 获取当前的写入位置 
  6.     int currentPos = this.wrotePosition.get(); 
  7.  
  8.     // 如果当前还是可写的 
  9.     if (currentPos < this.fileSize) { 
  10.  
  11.         // 获取到实际的写入句柄 
  12.         ByteBuffer byteBuffer = this.mappedByteBuffer.slice(); 
  13.  
  14.         // 调整当前写入位置 
  15.         byteBuffer.position(currentPos); 
  16.  
  17.         // 记录信息 
  18.         AppendMessageResult result = null
  19.  
  20.         // 调用回调函数中的实际写入操作 
  21.         result = cb.doAppend(this.getFileFromOffset(), byteBuffer, this.fileSize - currentPos, message); 
  22.  
  23.         this.wrotePosition.addAndGet(result.getWroteBytes()); 
  24.         this.storeTimestamp = result.getStoreTimestamp(); 
  25.         return result; 
  26.     } 
  27.  
  28.     ... 

MappedPartitionQueue

MappedPartitionQueue 用来管理多个物理上的映射文件,其构造函数如下:

  1. // 存放所有的映射文件 
  2. private final CopyOnWriteArrayList<MappedPartition> mappedPartitions = new CopyOnWriteArrayList<MappedPartition>(); 
  3.  
  4. ... 
  5.  
  6. /** 
  7.     * Description  默认构造函数 
  8.     * 
  9.     * @param storePath                      传入的存储文件目录,有可能传入 MessageStore 目录或者 ConsumeQueue 目录 
  10.     * @param mappedFileSize 
  11.     * @param allocateMappedPartitionService 
  12.     */ 
  13. public MappedPartitionQueue(final String storePath, int mappedFileSize, 
  14.                             AllocateMappedPartitionService allocateMappedPartitionService) { 
  15.     this.storePath = storePath; 
  16.     this.mappedFileSize = mappedFileSize; 
  17.     this.allocateMappedPartitionService = allocateMappedPartitionService; 
  18. }{} 

这里以 load 函数为例说明其加载过程:

  1. /** 
  2.     * Description 加载内存映射文件序列 
  3.     * 
  4.     * @return 
  5.     */ 
  6. public boolean load() { 
  7.  
  8.     // 读取存储路径 
  9.     File dir = new File(this.storePath); 
  10.  
  11.     // 列举目录下所有文件 
  12.     File[] files = dir.listFiles(); 
  13.  
  14.     // 如果文件不为空,则表示有必要加载 
  15.     if (files != null) { 
  16.  
  17.         // 重排序 
  18.         Arrays.sort(files); 
  19.  
  20.         // 遍历所有的文件 
  21.         for (File file : files) { 
  22.  
  23.             // 如果碰到某个文件尚未填满,则返回加载完毕 
  24.             if (file.length() != this.mappedFileSize) { 
  25.                 log.warning(file + "\t" + file.length() 
  26.                         + " length not matched message store config value, ignore it"); 
  27.                 return true
  28.             } 
  29.  
  30.             // 否则加载文件 
  31.             try { 
  32.  
  33.                 // 实际读取文件 
  34.                 MappedPartition mappedPartition = new MappedPartition(file.getPath(), mappedFileSize); 
  35.  
  36.                 // 设置当前文件指针到文件尾 
  37.                 mappedPartition.setWrotePosition(this.mappedFileSize); 
  38.                 mappedPartition.setFlushedPosition(this.mappedFileSize); 
  39.  
  40.                 // 将文件放置到 MappedFiles 数组中 
  41.                 this.mappedPartitions.add(mappedPartition); 
  42. //                    log.info("load " + file.getPath() + " OK"); 
  43.  
  44.             } catch (IOException e) { 
  45.                 log.warning("load file " + file + " error"); 
  46.                 return false
  47.             } 
  48.         } 
  49.     } 
  50.  
  51.     return true

异步预创建文件

处于性能的考虑,MappedPartitionQueue 还会提前创建文件,在 getLastMappedFileOrCreate 函数中,当 allocateMappedPartitionService 存在的情况下则会调用该异步服务预创建文件:

  1. /** 
  2.     * Description 根据起始偏移量查找最后一个文件 
  3.     * 
  4.     * @param startOffset 
  5.     * @return 
  6. */ 
  7. public MappedPartition getLastMappedFileOrCreate(final long startOffset) { 
  8.  
  9.     ... 
  10.  
  11.     // 如果有必要创建文件 
  12.     if (createOffset != -1) { 
  13.  
  14.         // 获取到下一个文件的路径与文件名 
  15.         String nextFilePath = this.storePath + File.separator + FSExtra.offset2FileName(createOffset); 
  16.  
  17.         // 以及下下个文件的路径与文件名 
  18.         String nextNextFilePath = this.storePath + File.separator 
  19.                 + FSExtra.offset2FileName(createOffset + this.mappedFileSize); 
  20.  
  21.         // 指向待创建的映射文件句柄 
  22.         MappedPartition mappedPartition = null
  23.  
  24.         // 判断是否存在创建映射文件的服务 
  25.         if (this.allocateMappedPartitionService != null) { 
  26.  
  27.             // 使用服务创建 
  28.             mappedPartition = this.allocateMappedPartitionService.putRequestAndReturnMappedFile(nextFilePath, 
  29.                     nextNextFilePath, this.mappedFileSize); 
  30.             // 进行预热处理 
  31.         } else { 
  32.  
  33.             // 否则直接创建 
  34.             try { 
  35.                 mappedPartition = new MappedPartition(nextFilePath, this.mappedFileSize); 
  36.             } catch (IOException e) { 
  37.                 log.warning("create mappedPartition exception"); 
  38.             } 
  39.         } 
  40.  
  41.         ... 
  42.  
  43.         return mappedPartition; 
  44.     } 
  45.  
  46.     return mappedPartitionLast; 

这里的 AllocateMappedPartitionService 则会不间断地执行创建文件的请求:

  1. @Override 
  2. public void run() { 
  3.  
  4.     ... 
  5.  
  6.     // 循环执行文件分配请求 
  7.     while (!this.isStopped() && this.mmapOperation()) {} 
  8.     ... 
  9.  
  10.  
  11. /** 
  12.     * Description 循环执行映射文件预分配 
  13.     * 
  14.     * @Exception Only interrupted by the external thread, will return false 
  15.     */ 
  16. private boolean mmapOperation() { 
  17.  
  18.     ... 
  19.  
  20.     // 执行操作 
  21.     try { 
  22.  
  23.         // 取出最新的执行对象 
  24.         req = this.requestQueue.take(); 
  25.  
  26.         // 取得待执行对象在请求表中的实例 
  27.         AllocateRequest expectedRequest = this.requestTable.get(req.getFilePath()); 
  28.  
  29.         ... 
  30.  
  31.         // 判断是否已经存在创建好的对象 
  32.         if (req.getMappedPartition() == null) { 
  33.  
  34.             // 记录起始创建时间 
  35.             long beginTime = System.currentTimeMillis(); 
  36.  
  37.             // 构建内存映射文件对象 
  38.             MappedPartition mappedPartition = new MappedPartition(req.getFilePath(), req.getFileSize()); 
  39.  
  40.             ... 
  41.  
  42.             // 进行文件预热,仅预热 MessageStore 
  43.             if (mappedPartition.getFileSize() >= mapedFileSizeCommitLog && isWarmMappedFileEnable) { 
  44.                 mappedPartition.warmMappedFile(); 
  45.             } 
  46.  
  47.             // 将创建好的对象回写到请求中 
  48.             req.setMappedPartition(mappedPartition); 
  49.  
  50.             // 异常设置为 false 
  51.             this.hasException = false
  52.  
  53.             // 成功设置为 true 
  54.             isSuccess = true
  55.         } 
  56.     ... 

异步 Flush

EmbeddedMessageQueue 中还包含了某个 flushAndUnmapPartitionServices 用于异步 Flush 文件并且完成不用映射文件的关闭操作。该服务的核心代码如下:

  1. private final ConcurrentLinkedQueue<MappedPartition> mappedPartitions = new ConcurrentLinkedQueue<>(); 
  2.  
  3. ... 
  4.  
  5. @Override 
  6. public void run() { 
  7.  
  8.     while (!this.isStopped()) { 
  9.  
  10.         int interval = 100; 
  11.  
  12.         try { 
  13.  
  14.             if (this.mappedPartitions.size() > 0) { 
  15.  
  16.                 long startTime = now(); 
  17.  
  18.                 // 取出待处理的 MappedPartition 
  19.                 MappedPartition mappedPartition = this.mappedPartitions.poll(); 
  20.  
  21.                 // 将当前内容写入到磁盘 
  22.                 mappedPartition.flush(0); 
  23.  
  24.                 // 释放当前不需要使用的空间 
  25.                 mappedPartition.cleanup(); 
  26.  
  27.                 long past = now() - startTime; 
  28.  
  29. //                    EmbeddedProducer.flushEclipseTime.addAndGet(past); 
  30.  
  31.                 if (past > 500) { 
  32.                     log.info("Flush data to disk and unmap MappedPartition costs " + past + " ms:" + mappedPartition.getFileName()); 
  33.                 } 
  34.             } else { 
  35.                 // 定时进行 Flush 操作 
  36.                 this.waitForRunning(interval); 
  37.             } 
  38.  
  39.  
  40.         } catch (Throwable e) { 
  41.             log.warning(this.getServiceName() + " service has exception. "); 
  42.         } 
  43.  
  44.     } 
  45.  

这里的 mappedPartitions 即是在上文介绍的当添加消息且返回为 END_OF_FILE 时候添加进来的。

LocalMessageQueue

源代码参考这里

消息存储

LocalMessageQueue 中采用了中心化的消息存储方案,其提供的 putMessage / putMessages 函数实际上会调用内置 MessageStore 对象的消息写入函数:

  1. // 使用 MessageStore 进行提交 
  2. PutMessageResult result = this.messageStore.putMessage(message); 

而 MessageStore 即是存放所有真实消息的中心存储,LocalMessageQueue 中支持更为复杂的消息属性:

序号消息存储结构备注长度(字节数)1TOTALSIZE消息大小42MAGICCODE消息的 MAGIC CODE43BODYCRC消息体 BODY CRC,用于重启时校验44QUEUEID队列编号,queueID45QUEUEOFFSET自增值,不是真正的 consume queue 的偏移量,可以代表这个队列中消息的个数,要通过这个值查找到 consume queue 中数据,QUEUEOFFSET * 12 才是偏移地址86PHYSICALOFFSET消息在 commitLog 中的物理起始地址偏移量87STORETIMESTAMP存储时间戳88BODY前 4 个字节存放消息体大小值,后 bodyLength 大小的空间存储消息体内容4 + bodyLength9TOPICORQUEUENAME前 1 个字节存放 Topic 大小,后存放 topicOrQueueNameLength 大小的主题名1 + topicOrQueueNameLength10headers*前 2 个字节(short)存放头部大小,后存放 headersLength 大小的头部数据2 + headersLength11properties*前 2 个字节(short)存放属性值大小,后存放 propertiesLength 大小的属性数据2 + propertiesLength

其构造函数中初始化创建的 MappedPartitionQueue 是按照固定大小(默认单文件 1G)的映射文件组:

  1. // 构造映射文件类 
  2. this.mappedPartitionQueue = new MappedPartitionQueue( 
  3.         ((LocalMessageQueueConfig) this.messageStore.getMessageQueueConfig()).getStorePathCommitLog(), 
  4.         mapedFileSizeCommitLog, 
  5.         messageStore.getAllocateMappedPartitionService(), 
  6.         this.flushMessageStoreService 
  7. ); 

构建 ConsumeQueue

不同于 EmbeddedMessageQueue,LocalMessageQueue 并没有在初次提交消息时就直接写入按照 Topic-queueId 划分的存储内;而是依赖于内置的 PostPutMessageService :

  1. /** 
  2.     * Description 执行消息后操作 
  3.     */ 
  4. private void doReput() { 
  5.  
  6.     for (boolean doNext = true; this.isCommitLogAvailable() && doNext; ) { 
  7.  
  8.         ... 
  9.  
  10.         // 读取当前的消息 
  11.         SelectMappedBufferResult result = this.messageStore.getMessageStore().getData(reputFromOffset); 
  12.  
  13.  
  14.         // 如果消息不存在,则停止当前操作 
  15.         if (result == null) { 
  16.             doNext = false
  17.             continue
  18.         } 
  19.         try { 
  20.  
  21.             // 获取当前消息的起始位置 
  22.             this.reputFromOffset = result.getStartOffset(); 
  23.  
  24.             // 顺序读取所有消息 
  25.             for (int readSize = 0; readSize < result.getSize() && doNext; ) { 
  26.  
  27.                 // 读取当前位置的消息 
  28.                 PostPutMessageRequest postPutMessageRequest = 
  29.                         checkMessageAndReturnSize(result.getByteBuffer()); 
  30.  
  31.                 int size = postPutMessageRequest.getMsgSize(); 
  32.  
  33.                 readSpendTime.addAndGet(now() - startTime); 
  34.  
  35.                 startTime = now(); 
  36.                 // 如果处理成功 
  37.                 if (postPutMessageRequest.isSuccess()) { 
  38.                     if (size > 0) { 
  39.  
  40.                         // 执行消息写入到 ConsumeQueue 的操作 
  41.                         this.messageStore.putMessagePositionInfo(postPutMessageRequest); 
  42.  
  43.                         // 修正当前读取的位置 
  44.                         this.reputFromOffset += size
  45.                         readSize += size
  46.  
  47.                     } else if (size == 0) { 
  48.                         this.reputFromOffset = this.messageStore.getMessageStore().rollNextFile(this.reputFromOffset); 
  49.                         readSize = result.getSize(); 
  50.                     } 
  51.  
  52.                     putSpendTime.addAndGet(now() - startTime); 
  53.  
  54.                 } else if (!postPutMessageRequest.isSuccess()) { 
  55.  
  56.                     ... 
  57.                 } 
  58.             } 
  59.  
  60.         } finally { 
  61.             result.release(); 
  62.         } 
  63.  
  64.     } 

而在 putMessagePositionInfo 函数中即进行实际的 ConsumeQueue 创建:

  1. /** 
  2.     * Description 将消息的位置放置到 ConsumeQueue 中 
  3.     * 
  4.     * @param postPutMessageRequest 
  5.     */ 
  6. public void putMessagePositionInfo(PostPutMessageRequest postPutMessageRequest) { 
  7.  
  8.     // 寻找或者创建 ConsumeQueue 
  9.     ConsumeQueue cq = this.findConsumeQueue(postPutMessageRequest.getTopic(), postPutMessageRequest.getQueueId()); 
  10.  
  11.     // 将消息放置到 ConsumeQueue 中合适的位置 
  12.     cq.putMessagePositionInfoWrapper(postPutMessageRequest.getCommitLogOffset(), postPutMessageRequest.getMsgSize(), postPutMessageRequest.getConsumeQueueOffset()); 
  13.  
  14.  
  15. /** 
  16.     * Description 根据主题与 QueueId 查找 ConsumeQueue,如果不存在则创建 
  17.     * 
  18.     * @param topic 
  19.     * @param queueId 
  20.     * @return 
  21. */ 
  22. public ConsumeQueue findConsumeQueue(String topic, int queueId) { 
  23.     ConcurrentHashMap<Integer, ConsumeQueue> map = consumeQueueTable.get(topic); 
  24.  
  25.     ... 
  26.  
  27.     // 判断该主题下是否存在 queueId,不存在则创建 
  28.     ConsumeQueue logic = map.get(queueId); 
  29.  
  30.     // 如果获取为空,则创建新的 ConsumeQueue 
  31.     if (null == logic) { 
  32.  
  33.         ConsumeQueue newLogic = new ConsumeQueue(// 
  34.                 topic, // 主题 
  35.                 queueId, // queueId 
  36.                 LocalMessageQueueConfig.mapedFileSizeConsumeQueue, // 映射文件尺寸 
  37.                 this); 
  38.  
  39.  
  40.         ConsumeQueue oldLogic = map.putIfAbsent(queueId, newLogic); 
  41.  
  42.         ... 
  43.     } 
  44.  
  45.     return logic; 

而在 ConsumeQueue 的构造函数中完成实际的文件映射与读取:

  1. /** 
  2.     * Description 主要构造函数 
  3.     * 
  4.     * @param topic 
  5.     * @param queueId 
  6.     * @param mappedFileSize 
  7.     * @param localMessageStore 
  8.     */ 
  9. public ConsumeQueue( 
  10.         final String topic, 
  11.         final int queueId, 
  12.         final int mappedFileSize, 
  13.         final LocalMessageQueue localMessageStore) { 
  14.  
  15.     ... 
  16.  
  17.     // 当前队列的路径 
  18.     String queueDir = this.storePath 
  19.             + File.separator + topic 
  20.             + File.separator + queueId; 
  21.  
  22.     // 初始化内存映射队列 
  23.     this.mappedPartitionQueue = new MappedPartitionQueue(queueDir, mappedFileSize, null); 
  24.  
  25.     this.byteBufferIndex = ByteBuffer.allocate(CQ_STORE_UNIT_SIZE); 
  26.  

ConsumeQueue 的文件格式则相对简单:

  1. // ConsumeQueue 文件内存放的单条 Message 尺寸 
  2. // 1 | MessageStore Offset | int 8 Byte 
  3. // 2 | Size | short 8 Byte 

消息拉取

在 LocalPullConsumer 拉取消息时,设置的批量拉取机制;即一次性从 LocalMessageQueue 拉取多条消息到本地,然后再批次返回给本地进行处理(假设处理也有一定耗时)。在批次拉取的函数中,我们首先需要获取当前 Consumer 处理的主题与队列编号对应的 ConsumeQueue 是否包含数据,然后再申请具体的读取句柄并且占用该队列:

  1. /** 
  2.     * Description 批量抓取消息,注意,这里只进行预抓取,仅当消费者真正获取后才会修正读取偏移量 
  3.     */ 
  4. private void batchPoll() { 
  5.     // 如果是 LocalMessageQueue 
  6.     // 执行预抓取 
  7.     LocalMessageQueue localMessageStore = (LocalMessageQueue) this.messageQueue; 
  8.  
  9.     // 获取当前待抓取的桶名 
  10.     String bucket = bucketList.get((lastIndex) % (bucketList.size())); 
  11.  
  12.     // 首先获取待抓取的队列和偏移 
  13.     long offsetInQueue = localMessageStore.getConsumerScheduler().queryOffsetAndLock("127.0.0.1:" + this.refId, bucket, this.getQueueId()); 
  14.  
  15.     // 如果当前待抓取的 queueId 已经被占用,则直接切换到下一个主题 
  16.     if (offsetInQueue == -2) { 
  17.         // 将当前主题设置为 true 
  18.         this.isFinishedTable.put(bucket, true); 
  19.  
  20.         // 重置当前的 LastIndex 或者 RefOffset,即 queueId 
  21.         this.resetLastIndexOrRefOffsetWhenNotFound(); 
  22.  
  23.     } else { 
  24.  
  25.         // 获取到了有效的队列偏移量之后,开始尝试获取消息 
  26.         consumerOffsetTable.put(bucket, new AtomicLong(offsetInQueue)); 
  27.  
  28.         // 设置每次最多抓一个文件内包含的消息数,等价于变相的一次性读完,注意,这里的数目还受到单个文件尺寸的限制 
  29.         GetMessageResult getMessageResult = localMessageStore.getMessage(bucket, this.getQueueId(), this.consumerOffsetTable.get(bucket).get() + 1, mapedFileSizeConsumeQueue / ConsumeQueue.CQ_STORE_UNIT_SIZE); 
  30.  
  31.         // 如果没有找到数据,则切换到下一个 
  32.         if (getMessageResult.getStatus() != GetMessageStatus.FOUND) { 
  33.  
  34.             // 将当前主题设置为 true 
  35.             this.isFinishedTable.put(bucket, true); 
  36.  
  37.             this.resetLastIndexOrRefOffsetWhenNotFound(); 
  38.  
  39.         } else { 
  40.  
  41.             // 这里不考虑 Consumer 被恶意干掉的情况,因此直接更新远端的 Offset 值 
  42.             localMessageStore.getConsumerScheduler().updateOffset("127.0.0.1:" + this.refId, bucket, this.getQueueId(), consumerOffsetTable.get(bucket).addAndGet(getMessageResult.getMessageCount())); 
  43.  
  44.             // 首先从文件系统中一次性读出所有的消息 
  45.             ArrayList<DefaultBytesMessage> messages = readMessagesFromGetMessageResult(getMessageResult); 
  46.  
  47.             // 将消息添加到队列中 
  48.             this.messages.addAll(messages); 
  49.  
  50.             // 本次抓取成功后才开始抓取下一个 
  51.             lastIndex++; 
  52.  
  53.         } 
  54.     } 
  55.  

消费者调度

ConsumerScheduler 为我们提供了核心的消费者调度功能,其内置的 ConsumerOffsetManager 包含了两个核心存储:

  1. // 存放映射到内存中 
  2. private ConcurrentHashMap<String/* topic */, ConcurrentHashMap<Integer/*queueId*/, Long>> offsetTable = 
  3.         new ConcurrentHashMap<String, ConcurrentHashMap<Integer, Long>>(512); 
  4.  
  5. // 存放某个 Topic 下面的某个 Queue 被某个 Consumer 占用的信息 
  6. private ConcurrentHashMap<String/* topic */, ConcurrentHashMap<Integer/*queueId*/, String/*refId*/>> queueIdOccupiedByConsumerTable = 
  7.         new ConcurrentHashMap<String, ConcurrentHashMap<Integer, String>>(512); 

分别对应了某个 ConsumeQueue 被消费的进度和被消费者的占用信息。同时 ConsumerOffsetManager 还提供了基于 JSON 格式的持久化功能,并且通过 ConsumerScheduler 中的定期服务 scheduledExecutorService 进行自动定期持久化。在消息提交阶段,LocalMessageQueue 会自动调用 updateOffset 函数更初始化某个 ConsumeQueue 的偏移情况(在恢复时也会使用):

  1. public void updateOffset(final String topic, final int queueId, final long offset) { 
  2.  
  3.     this.consumerOffsetManager.commitOffset("Broker Inner", topic, queueId, offset); 
  4.  

而某个 Consumer 在初次拉取时,会调用 queryOffsetAndLock 函数来查询某个 ConsumeQueue 的可拉取情况:

  1. /** 
  2.     * Description 修正某个 ConsumerOffset 队列中的值 
  3.     * 
  4.     * @param topic 
  5.     * @param queueId 
  6.     * @return 
  7.     */ 
  8. public long queryOffsetAndLock(final String clientHostAndPort, final String topic, final int queueId) { 
  9.  
  10.     String key = topic; 
  11.  
  12.     // 首先判断该 Topic-queueId 是否被占用 
  13.     if (this.queueIdOccupiedByConsumerTable.containsKey(topic)) { 
  14.  
  15.         ... 
  16.     } 
  17.  
  18.     // 如果没有被占用,则此时宣告占用 
  19.     ConcurrentHashMap<Integer, String> consumerQueueIdMap = this.queueIdOccupiedByConsumerTable.get(key); 
  20.  
  21.     ... 
  22.  
  23.     // 真实进行查找操作 
  24.     ConcurrentHashMap<Integer, Long> map = this.offsetTable.get(key); 
  25.     if (null != map) { 
  26.         Long offset = map.get(queueId); 
  27.         if (offset != null
  28.             return offset; 
  29.     } 
  30.  
  31.     // 默认返回值为 -1 
  32.     return -1; 

并且在拉取完毕后调用 updateOffset 函数来更新拉取进度。

消息读取

在某个 Consumer 通过 ConsumerManager 获取可用的拉取偏移量之后,即从 LocalMessageQueue 中进行真实地消息读取操作:

  1. /** 
  2.     * Description Consumer 从存储中读取数据的接口 
  3.     * 
  4.     * @param topic 
  5.     * @param queueId 
  6.     * @param offset     下一个开始抓取的起始下标 
  7.     * @param maxMsgNums 
  8.     * @return 
  9.     */ 
  10. public GetMessageResult getMessage(final String topic, final int queueId, final long offset, final int maxMsgNums) { 
  11.  
  12.         ... 
  13.  
  14.         // 根据 Topic 与 queueId 构建消费者队列 
  15.         ConsumeQueue consumeQueue = findConsumeQueue(topic, queueId); 
  16.  
  17.  
  18.         // 保证当前 ConsumeQueue 存在 
  19.         if (consumeQueue != null) { 
  20.  
  21.             // 获取当前 ConsumeQueue 中包含的最小的消息在 MessageStore 中的位移 
  22.             minOffset = consumeQueue.getMinOffsetInQueue(); 
  23.  
  24.             // 注意,最大的位移地址即是不可达地址,是当前所有消息的下一个消息的下标 
  25.             maxOffset = consumeQueue.getMaxOffsetInQueue(); 
  26.  
  27.             // 如果 maxOffset 为零,则表示没有可用消息 
  28.             if (maxOffset == 0) { 
  29.                 status = GetMessageStatus.NO_MESSAGE_IN_QUEUE; 
  30.                 nextBeginOffset = 0; 
  31.             } else if (offset < minOffset) { 
  32.                 status = GetMessageStatus.OFFSET_TOO_SMALL; 
  33.                 nextBeginOffset = minOffset; 
  34.             } else if (offset == maxOffset) { 
  35.                 status = GetMessageStatus.OFFSET_OVERFLOW_ONE; 
  36.                 nextBeginOffset = offset; 
  37.             } else if (offset > maxOffset) { 
  38.                 status = GetMessageStatus.OFFSET_OVERFLOW_BADLY; 
  39.                 if (0 == minOffset) { 
  40.                     nextBeginOffset = minOffset; 
  41.                 } else { 
  42.                     nextBeginOffset = maxOffset; 
  43.                 } 
  44.             } else { 
  45.  
  46.                 // 根据偏移量获取当前 ConsumeQueue 的缓存 
  47.                 SelectMappedBufferResult bufferConsumeQueue = consumeQueue.getIndexBuffer(offset); 
  48.  
  49.                 if (bufferConsumeQueue != null) { 
  50.                     try { 
  51.                         status = GetMessageStatus.NO_MATCHED_MESSAGE; 
  52.  
  53.                         long nextPhyFileStartOffset = Long.MIN_VALUE; 
  54.                         long maxPhyOffsetPulling = 0; 
  55.  
  56.                         int i = 0; 
  57.  
  58.                         // 设置每次获取的最大消息数 
  59.                         final int maxFilterMessageCount = Math.max(16000, maxMsgNums * ConsumeQueue.CQ_STORE_UNIT_SIZE); 
  60.  
  61.                         // 遍历所有的 Consume Queue 中的消息指针 
  62.                         for (; i < bufferConsumeQueue.getSize() && i < maxFilterMessageCount; i += ConsumeQueue.CQ_STORE_UNIT_SIZE) { 
  63.                             long offsetPy = bufferConsumeQueue.getByteBuffer().getLong(); 
  64.                             int sizePy = bufferConsumeQueue.getByteBuffer().getInt(); 
  65.  
  66.                             maxPhyOffsetPulling = offsetPy; 
  67.  
  68.                             if (nextPhyFileStartOffset != Long.MIN_VALUE) { 
  69.                                 if (offsetPy < nextPhyFileStartOffset) 
  70.                                     continue
  71.                             } 
  72.  
  73.                             boolean isInDisk = checkInDiskByCommitOffset(offsetPy, maxOffsetPy); 
  74.  
  75.                             if (isTheBatchFull(sizePy, maxMsgNums, getResult.getBufferTotalSize(), getResult.getMessageCount(), 
  76.                                     isInDisk)) { 
  77.                                 break; 
  78.                             } 
  79.  
  80.                             // 从 MessageStore 中获取消息 
  81.                             SelectMappedBufferResult selectResult = this.messageStore.getMessage(offsetPy, sizePy); 
  82.  
  83.                             // 如果没有获取到数据,则切换到下一个文件继续 
  84.                             if (null == selectResult) { 
  85.                                 if (getResult.getBufferTotalSize() == 0) { 
  86.                                     status = GetMessageStatus.MESSAGE_WAS_REMOVING; 
  87.                                 } 
  88.  
  89.                                 nextPhyFileStartOffset = this.messageStore.rollNextFile(offsetPy); 
  90.                                 continue
  91.                             } 
  92.  
  93.                             // 如果获取到了,则返回结果 
  94.                             getResult.addMessage(selectResult); 
  95.                             status = GetMessageStatus.FOUND; 
  96.                             nextPhyFileStartOffset = Long.MIN_VALUE; 
  97.                         } 
  98.  
  99.                         nextBeginOffset = offset + (i / ConsumeQueue.CQ_STORE_UNIT_SIZE); 
  100.  
  101.                         long diff = maxOffsetPy - maxPhyOffsetPulling; 
  102.  
  103.                         // 获取当前内存情况 
  104.                         long memory = (long) (getTotalPhysicalMemorySize() 
  105.                                 * (LocalMessageQueueConfig.accessMessageInMemoryMaxRatio / 100.0)); 
  106.  
  107.                         getResult.setSuggestPullingFromSlave(diff > memory); 
  108.  
  109.                     } finally { 
  110.  
  111.                         bufferConsumeQueue.release(); 
  112.                     } 
  113.                 } else { 
  114.                     status = GetMessageStatus.OFFSET_FOUND_NULL; 
  115.                     nextBeginOffset = consumeQueue.rollNextFile(offset); 
  116.                     log.warning("consumer request topic: " + topic + "offset: " + offset + " minOffset: " + minOffset + " maxOffset: " 
  117.                             + maxOffset + ", but access logic queue failed."); 
  118.                 } 
  119.             } 
  120.         } else { 
  121.             ... 
  122.         } 
  123.  
  124.         ... 
  125.  

注意,这里返回的其实只是消息在 MessageStore 中的存放地址,真实地消息读取还需要通过 readMessagesFromGetMessageResult 函数:

  1. /** 
  2.     * Description 从 GetMessageResult 中抓取全部的消息 
  3.     * 
  4.     * @param getMessageResult 
  5.     * @return 
  6.     */ 
  7. public static ArrayList<DefaultBytesMessage> readMessagesFromGetMessageResult(final GetMessageResult getMessageResult) { 
  8.  
  9.     ArrayList<DefaultBytesMessage> messages = new ArrayList<>(); 
  10.  
  11.     try { 
  12.         List<ByteBuffer> messageBufferList = getMessageResult.getMessageBufferList(); 
  13.         for (ByteBuffer bb : messageBufferList) { 
  14.  
  15.             messages.add(readMessageFromByteBuffer(bb)); 
  16.         } 
  17.     } finally { 
  18.         getMessageResult.release(); 
  19.     } 
  20.  
  21.     // 获取字节数组 
  22.  
  23.     return messages; 
  24.  
  25. /** 
  26.     * Description 从输入的 ByteBuffer 中反序列化消息对象 
  27.     * 
  28.     * @return 0 Come the end of the file // >0 Normal messages // -1 Message checksum failure 
  29.     */ 
  30. public static DefaultBytesMessage readMessageFromByteBuffer(java.nio.ByteBuffer byteBuffer) { 
  31.  
  32.     // 1 TOTAL SIZE 
  33.     int totalSize = byteBuffer.getInt(); 
  34.  
  35.     // 2 MAGIC CODE 
  36.     int magicCode = byteBuffer.getInt(); 
  37.  
  38.     switch (magicCode) { 
  39.         case MESSAGE_MAGIC_CODE: 
  40.             break; 
  41.         case BLANK_MAGIC_CODE: 
  42.             return null
  43.         default
  44.             log.warning("found a illegal magic code 0x" + Integer.toHexString(magicCode)); 
  45.             return null
  46.     } 
  47.  
  48.     byte[] bytesContent = new byte[totalSize]; 
  49.  
  50.     ... 
  51.  
  52.  

 【本文是51CTO专栏作者“张梓雄 ”的原创文章,如需转载请通过51CTO与作者联系】

戳这里,看该作者更多好文

责任编辑:武晓燕 来源: 51CTO专栏
相关推荐

2022-12-09 08:40:56

高性能内存队列

2022-06-09 08:36:56

高性能Disruptor模式

2011-10-21 14:20:59

高性能计算HPC虚拟化

2011-10-25 13:13:35

HPC高性能计算Platform

2017-08-16 11:00:38

TCPIP协议

2020-06-05 07:20:41

测试自动化环境

2011-12-15 13:28:57

2020-06-17 16:43:40

网络IO框架

2009-06-03 14:24:12

ibmdwWebSphere

2009-10-29 09:11:50

Juniper高性能网络

2011-02-23 09:49:40

ASP.NET

2011-02-13 09:17:02

ASP.NET

2023-12-26 00:58:53

Web应用Go语言

2011-02-15 09:31:56

ASP.NET

2017-10-11 15:08:28

消息队列常见

2021-03-10 09:52:38

开发技能架构

2011-02-16 09:08:27

ASP.NET

2023-11-07 10:01:34

2013-07-31 10:11:27

2011-10-24 09:43:18

高性能计算HPC云计算
点赞
收藏

51CTO技术栈公众号