深入剖析 RocketMQ 源码 - 消息存储模块

RocketMQ-RocketMQ⾼性能核心原理与源码剖析(上) 实际上,在应用中,可以通过producer.setSendMessageWithVIPChannel(true),让少量比较重要的producer走VIP的通道。这个Cotroller对象就跟MVC中的Controller是很类似的,都是响应客户端的请求。我们现在不需要了解这些核心组件的具体功能,只要有个大概,Broker中有一大堆的功能组件负责具体的业务。​ 从NameServer启动和关闭这两个关键步骤,我们可以总结出NameServer的组件其实并不是很多,整个NameServer的结构是这样的; 阅读详情

一、简介

RocketMQ 是阿里巴巴开源的分布式消息中间件,它借鉴了 Kafka 实现,支持消息订阅与发布、顺序消息、事务消息、定时消息、消息回溯、死信队列等功能。RocketMQ 架构上主要分为四部分,如下图所示:

  • Producer:消息生产者,支持分布式集群方式部署。

  • Consumer:消息消费者,支持分布式集群方式部署。

  • NameServer:名字服务,是一个非常简单的 Topic 路由注册中心,支持 Broker 的动态注册与发现,Producer 和 Consumer 通过 NameServer 动态感知 Broker 的路由信息。

  • Broker:Broker 主要负责消息的存储、转发和查询。

本文基于 Apache RocketMQ 4.9.1 版本剖析 Broker 中的消息存储模块是如何设计的。

二、存储架构

RocketMQ 的消息文件路径如图所示。

CommitLog

消息主体以及元数据的存储主体,存储 Producer 端写入的消息主体内容,消息内容不是定长的。单个文件大小默认1G, 文件名长度为 20 位,左边补零,剩余为起始偏移量,比如 00000000000000000000 代表了第一个文件,起始偏移量为 0,文件大小为 1G=1073741824;当第一个文件写满了,第二个文件为 00000000001073741824,起始偏移量为 1073741824,以此类推。

ConsumeQueue

消息消费队列,Consumequeue 文件可以看成是基于 CommitLog 的索引文件。ConsumeQueue 文件采取定长设计,每一个条目共 20 个字节,分别为 8 字节的 CommitLog 物理偏移量、4 字节的消息长度、8 字节 tag hashcode,单个文件由 30W 个条目组成,可以像数组一样随机访问每一个条目,每个 ConsumeQueue 文件大小约 5.72M。

IndexFile

索引文件,提供了一种可以通过 key 或时间区间来查询消息的方法。单个 IndexFile 文件大小约为 400M,一个 IndexFile 可以保存 2000W 个索引,IndexFile 的底层存储设计类似 JDK 的 HashMap 数据结构。

其他文件:包括 config 文件夹,存放运行时配置信息;abort 文件,说明 Broker 是否正常关闭;checkpoint 文件,存储 Commitlog、ConsumeQueue、Index 文件最后一次刷盘时间戳。这些不在本文讨论的范围。

同 Kafka 相比,Kafka 每个 Topic 的每个 partition 对应一个文件,顺序写入,定时刷盘。但一旦单个 Broker 的 Topic 过多,顺序写将退化为随机写。而 RocketMQ 单个 Broker 所有 Topic 在同一个 CommitLog 中顺序写,是能够保证严格顺序写。RocketMQ 读取消息需要从 ConsumeQueue 中拿到消息实际物理偏移再去 CommitLog 读取消息内容,会造成随机读取。

2.1 Page Cache 和 mmap

在正式介绍 Broker 消息存储模块实现前,先说明下 Page Cache 和 mmap 这两个概念。

Page Cache 是 OS 对文件的缓存,用于加速对文件的读写。一般来说,程序对文件进行顺序读写的速度几乎接近于内存的读写速度,主要原因就是由于 OS 使用 Page Cache 机制对读写访问操作进行了性能优化,将一部分的内存用作 Page Cache。对于数据的写入,OS 会先写入至 Cache 内,随后通过异步的方式由 pdflush 内核线程将 Cache 内的数据刷盘至物理磁盘上。对于数据的读取,如果一次读取文件时出现未命中 Page Cache 的情况,OS 从物理磁盘上访问读取文件的同时,会顺序对其他相邻块的数据文件进行预读取。

mmap 是将磁盘上的物理文件直接映射到用户态的内存地址中,减少了传统 IO 将磁盘文件数据在操作系统内核地址空间的缓冲区和用户应用程序地址空间的缓冲区之间来回进行拷贝的性能开销。Java NIO 中的 FileChannel 提供了 map() 方法可以实现 mmap。FileChannel (文件通道)和 mmap (内存映射) 读写性能比较可以参照这篇文章。

2.2 Broker 模块

下图是 Broker 存储架构图,展示了 Broker 模块从收到消息到返回响应业务流转过程。

业务接入层:RocketMQ 基于 Netty 的 Reactor 多线程模型实现了底层通信。Reactor 主线程池 eventLoopGroupBoss 负责创建 TCP 连接,默认只有一个线程。连接建立后,再丢给 Reactor 子线程池 eventLoopGroupSelector 进行读写事件的处理。

defaultEventExecutorGroup 负责 SSL 验证、编解码、空闲检查、网络连接管理。然后根据 RomotingCommand 的业务请求码 code 去 processorTable 这个本地缓存变量中找到对应的 processor,封装成 task 任务后,提交给对应的业务 processor 处理线程池来执行。Broker 模块通过这四级线程池提升系统吞吐量。

业务处理层:处理各种通过 RPC 调用过来的业务请求,其中:

  • SendMessageProcessor 负责处理 Producer 发送消息的请求;

  • PullMessageProcessor 负责处理 Consumer 消费消息的请求;

  • QueryMessageProcessor 负责处理按照消息 Key 等查询消息的请求。

存储逻辑层:DefaultMessageStore 是 RocketMQ 的存储逻辑核心类,提供消息存储、读取、删除等能力。

文件映射层:把 Commitlog、ConsumeQueue、IndexFile 文件映射为存储对象 MappedFile。

数据传输层:支持基于 mmap 内存映射进行读写消息,同时也支持基于 mmap 进行读取消息、堆外内存写入消息的方式进行读写消息。

下面章节将从源码角度来剖析 RocketMQ 是如何实现高性能存储。

三、消息写入

以单个消息生产为例,消息写入时序逻辑如下图,业务逻辑如上文 Broker 存储架构所示在各层之间进行流转。

最底层消息写入核心代码在 CommitLog 的 asyncPutMessage 方法中,主要分为获取 MappedFile、往缓冲区写消息、提交刷盘请求三步。需要注意的是在这三步前后有自旋锁或 ReentrantLock 的加锁、释放锁,保证单个 Broker 写消息是串行的。

//org.apache.rocketmq.store.CommitLog::asyncPutMessage
public CompletableFuture<PutMessageResult> asyncPutMessage(final MessageExtBrokerInner msg) {
        ...
        putMessageLock.lock(); //spin or ReentrantLock ,depending on store config
        try {
            //获取最新的 MappedFile
            MappedFile mappedFile = this.mappedFileQueue.getLastMappedFile();
            ...
            //向缓冲区写消息
            result = mappedFile.appendMessage(msg, this.appendMessageCallback, putMessageContext);
            ...
            //提交刷盘请求
            CompletableFuture<PutMessageStatus> flushResultFuture = submitFlushRequest(result, msg);
            ...
        } finally {
            putMessageLock.unlock();
        }
        ...
    }

下面介绍这三步具体做了什么事情。

3.1 MappedFile 初始化

在 Broker 初始化时会启动管理 MappedFile 创建的 AllocateMappedFileService 异步线程。消息处理线程 和 AllocateMappedFileService 线程通过队列 requestQueue 关联。

消息写入时调用 AllocateMappedFileService 的 putRequestAndReturnMappedFile 方法往 requestQueue 放入提交创建 MappedFile 请求,这边会同时构建两个 AllocateRequest 放入队列。

AllocateMappedFileService 线程循环从 requestQueue 获取 AllocateRequest 来创建 MappedFile。消息处理线程通过 CountDownLatch 等待获取第一个 MappedFile 创建成功就返回。

当消息处理线程需要再次创建 MappedFile 时,此时可以直接获取之前已预创建的 MappedFile。这样通过预创建 MappedFile ,减少文件创建等待时间。

//org.apache.rocketmq.store.AllocateMappedFileService::putRequestAndReturnMappedFile
public MappedFile putRequestAndReturnMappedFile(String nextFilePath, String nextNextFilePath, int fileSize) {
    //请求创建 MappedFile
    AllocateRequest nextReq = new AllocateRequest(nextFilePath, fileSize);
    boolean nextPutOK = this.requestTable.putIfAbsent(nextFilePath, nextReq) == null;
    ...
    //请求预先创建下一个 MappedFile
    AllocateRequest nextNextReq = new AllocateRequest(nextNextFilePath, fileSize);
    boolean nextNextPutOK = this.requestTable.putIfAbsent(nextNextFilePath, nextNextReq) == null;
    ...
    //获取本次创建 MappedFile
    AllocateRequest result = this.requestTable.get(nextFilePath);
    ...
}
 
//org.apache.rocketmq.store.AllocateMappedFileService::run
public void run() {
    ..
    while (!this.isStopped() && this.mmapOperation()) {
    }
    ...
}
 
//org.apache.rocketmq.store.AllocateMappedFileService::mmapOperation
private boolean mmapOperation() {
    ...
    //从队列获取 AllocateRequest
    req = this.requestQueue.take();
    ...
    //判断是否开启堆外内存池
    if (messageStore.getMessageStoreConfig().isTransientStorePoolEnable()) {
        //开启堆外内存的 MappedFile
        mappedFile = ServiceLoader.load(MappedFile.class).iterator().next();
        mappedFile.init(req.getFilePath(), req.getFileSize(), messageStore.getTransientStorePool());
    } else {
        //普通 MappedFile
        mappedFile = new MappedFile(req.getFilePath(), req.getFileSize());
    }
    ...
    //MappedFile 预热
    if (mappedFile.getFileSize() >= this.messageStore.getMessageStoreConfig()
        .getMappedFileSizeCommitLog()
        &&
        this.messageStore.getMessageStoreConfig().isWarmMapedFileEnable()) {
        mappedFile.warmMappedFile(this.messageStore.getMessageStoreConfig().getFlushDiskType(),
            this.messageStore.getMessageStoreConfig().getFlushLeastPagesWhenWarmMapedFile());
    }
    req.setMappedFile(mappedFile);
    ...
}

每次新建普通 MappedFile 请求,都会创建 mappedByteBuffer,下面代码展示了 Java mmap 是如何实现的。

//org.apache.rocketmq.store.MappedFile::init
private void init(final String fileName, final int fileSize) throws IOException {
    ...
    this.fileChannel = new RandomAccessFile(this.file, "rw").getChannel();
    this.mappedByteBuffer = this.fileChannel.map(MapMode.READ_WRITE, 0, fileSize);
    ...
}

如果开启堆外内存,即 transientStorePoolEnable = true 时,mappedByteBuffer 只是用来读消息,堆外内存用来写消息,从而实现对于消息的读写分离。堆外内存对象不是每次新建 MappedFile 都需要创建,而是系统启动时根据堆外内存池大小就初始化好了。每个堆外内存 DirectByteBuffer 都与 CommitLog 文件大小相同,通过锁定住该堆外内存,确保不会被置换到虚拟内存中去。

//org.apache.rocketmq.store.TransientStorePool
public void init() {
    for (int i = 0; i < poolSize; i++) {
        //分配与 CommitLog 文件大小相同的堆外内存
        ByteBuffer byteBuffer = ByteBuffer.allocateDirect(fileSize);
        final long address = ((DirectBuffer) byteBuffer).address();
        Pointer pointer = new Pointer(address);
        //锁定堆外内存,确保不会被置换到虚拟内存中去
        LibC.INSTANCE.mlock(pointer, new NativeLong(fileSize));
        availableBuffers.offer(byteBuffer);
    }
}

上面的 mmapOperation 方法中有段 MappedFile 预热逻辑。为什么需要文件预热呢?文件预热怎么做的呢?

因为通过 mmap 映射,只是建立了进程虚拟内存地址与物理内存地址之间的映射关系,并没有将 Page Cache 加载至内存。读写数据时如果没有命中写 Page Cache 则发生缺页中断,从磁盘重新加载数据至内存,这样会影响读写性能。为了防止缺页异常,阻止操作系统将相关的内存页调度到交换空间(swap space),RocketMQ 通过对文件预热,文件预热实现如下。

//org.apache.rocketmq.store.MappedFile::warmMappedFile
public void warmMappedFile(FlushDiskType type, int pages) {
        ByteBuffer byteBuffer = this.mappedByteBuffer.slice();
        int flush = 0;
        //通过写入 1G 的字节 0 来让操作系统分配物理内存空间,如果没有填充值,操作系统不会实际分配物理内存,防止在写入消息时发生缺页异常
        for (int i = 0, j = 0; i < this.fileSize; i += MappedFile.OS_PAGE_SIZE, j++) {
            byteBuffer.put(i, (byte) 0);
            // force flush when flush disk type is sync
            if (type == FlushDiskType.SYNC_FLUSH) {
                if ((i / OS_PAGE_SIZE) - (flush / OS_PAGE_SIZE) >= pages) {
                    flush = i;
                    mappedByteBuffer.force();
                }
            }
 
            //prevent gc
            if (j % 1000 == 0) {
                Thread.sleep(0);
            }
        }
 
        //force flush when prepare load finished
        if (type == FlushDiskType.SYNC_FLUSH) {
            mappedByteBuffer.force();
        }
        ...
        this.mlock();
}
 
//org.apache.rocketmq.store.MappedFile::mlock
public void mlock() {
    final long beginTime = System.currentTimeMillis();
    final long address = ((DirectBuffer) (this.mappedByteBuffer)).address();
    Pointer pointer = new Pointer(address);
 
    //通过系统调用 mlock 锁定该文件的 Page Cache,防止其被交换到 swap 空间
    int ret = LibC.INSTANCE.mlock(pointer, new NativeLong(this.fileSize));
 
    //通过系统调用 madvise 给操作系统建议,说明该文件在不久的将来要被访问
    int ret = LibC.INSTANCE.madvise(pointer, new NativeLong(this.fileSize), LibC.MADV_WILLNEED);
}

综上所述,RocketMQ 每次都预创建一个文件来减少文件创建延迟,通过文件预热避免了读写时缺页异常。

3.2 消息写入

3.2.1 写入 CommitLog

CommitLog 中每条消息存储的逻辑视图如下图所示, TOTALSIZE 是整个消息占用存储空间大小。

下面表格说明下每条消息包含哪些字段,以及这些字段占用空间大小和字段简介。

消息的写入是调用MappedFile 的 appendMessagesInner方法。

//org.apache.rocketmq.store.MappedFile::appendMessagesInner
public AppendMessageResult appendMessagesInner(final MessageExt messageExt, final AppendMessageCallback cb,
        PutMessageContext putMessageContext) {
    //判断使用 DirectBuffer 还是 MappedByteBuffer 进行写操作
    ByteBuffer byteBuffer = writeBuffer != null ? writeBuffer.slice() : this.mappedByteBuffer.slice();
    ..
    byteBuffer.position(currentPos);
    AppendMessageResult result  = cb.doAppend(this.getFileFromOffset(), byteBuffer, this.fileSize - currentPos,
                    (MessageExtBrokerInner) messageExt, putMessageContext);
    ..
    return result;
}
 
//org.apache.rocketmq.store.CommitLog::doAppend
public AppendMessageResult doAppend(final long fileFromOffset, final ByteBuffer byteBuffer, final int maxBlank,
    final MessageExtBrokerInner msgInner, PutMessageContext putMessageContext) {
    ...
    ByteBuffer preEncodeBuffer = msgInner.getEncodedBuff();
    ...
    //这边只是将消息写入缓冲区,还未实际刷盘
    byteBuffer.put(preEncodeBuffer);
    msgInner.setEncodedBuff(null);
    ...
    return result;
}

至此,消息最终写入 ByteBuffer,还没有持久到磁盘,具体何时持久化,下一小节会具体讲刷盘机制。这边有个疑问 ConsumeQueue 和 IndexFile 是怎么写入的?

答案是在存储架构图中存储逻辑层的 ReputMessageService。MessageStore 在初始化的时候,会启动一个 ReputMessageService 异步线程,它启动后便会在循环中不断调用 doReput 方法,用来通知 ConsumeQueue 和 IndexFile 进行更新。ConsumeQueue 和 IndexFile 之所以可以异步更新是因为 CommitLog 中保存了恢复 ConsumeQueue 和 IndexFile 所需队列和 Topic 等信息,即使 Broker 服务异常宕机,Broker 重启后可以根据 CommitLog 恢复 ConsumeQueue 和IndexFile。

//org.apache.rocketmq.store.DefaultMessageStore.ReputMessageService::run
public void run() {
    ...
    while (!this.isStopped()) {
        Thread.sleep(1);
         this.doReput();
    }
    ...
}
 
//org.apache.rocketmq.store.DefaultMessageStore.ReputMessageService::doReput
private void doReput() {
    ...
    //获取CommitLog中存储的新消息
    DispatchRequest dispatchRequest =
        DefaultMessageStore.this.commitLog.checkMessageAndReturnSize(result.getByteBuffer(), false, false);
    int size = dispatchRequest.getBufferSize() == -1 ? dispatchRequest.getMsgSize() : dispatchRequest.getBufferSize();
 
    if (dispatchRequest.isSuccess()) {
        if (size > 0) {
            //如果有新消息,则分别调用 CommitLogDispatcherBuildConsumeQueue、CommitLogDispatcherBuildIndex 进行构建 ConsumeQueue 和 IndexFile
            DefaultMessageStore.this.doDispatch(dispatchRequest);
    }
    ...
}

3.2.2 写入 ConsumeQueue

如下图所示,ConsumeQueue 每一条记录共 20 个字节,分别为 8 字节的 CommitLog 物理偏移量、4 字节的消息长度、8字节 tag hashcode。

ConsumeQueue 记录持久化逻辑如下。

//org.apache.rocketmq.store.ConsumeQueue::putMessagePositionInfo
private boolean putMessagePositionInfo(final long offset, final int size, final long tagsCode,
    final long cqOffset) {
    ...
    this.byteBufferIndex.flip();
    this.byteBufferIndex.limit(CQ_STORE_UNIT_SIZE);
    this.byteBufferIndex.putLong(offset);
    this.byteBufferIndex.putInt(size);
    this.byteBufferIndex.putLong(tagsCode);
 
    final long expectLogicOffset = cqOffset * CQ_STORE_UNIT_SIZE;
 
    MappedFile mappedFile = this.mappedFileQueue.getLastMappedFile(expectLogicOffset);
    if (mappedFile != null) {
        ...
        return mappedFile.appendMessage(this.byteBufferIndex.array());
    }
}

3.2.3 写入 IndexFile

IndexFile 的文件逻辑结构如下图所示,类似于 JDK 的 HashMap 的数组加链表结构。主要由 Header、Slot Table、Index Linked List 三部分组成。

Header:IndexFile 的头部,占 40 个字节。主要包含以下字段:

  • beginTimestamp:该 IndexFile 文件中包含消息的最小存储时间。

  • endTimestamp:该 IndexFile 文件中包含消息的最大存储时间。

  • beginPhyoffset:该 IndexFile 文件中包含消息的最小 CommitLog 文件偏移量。

  • endPhyoffset:该 IndexFile 文件中包含消息的最大 CommitLog 文件偏移量。

  • hashSlotcount:该 IndexFile 文件中包含的 hashSlot 的总数。

  • indexCount:该 IndexFile 文件中已使用的 Index 条目个数。

Slot Table:默认包含 500w 个 Hash 槽,每个 Hash 槽存储的是相同 hash 值的第一个 IndexItem 存储位置 。

Index Linked List:默认最多包含 2000w 个 IndexItem。其组成如下所示:

  • Key Hash:消息 key 的 hash,当根据 key 搜索时比较的是其 hash,在之后会比较 key 本身。

  • CommitLog Offset:消息的物理位移。

  • Timestamp:该消息存储时间与第一条消息的时间戳的差值。

  • Next Index Offset:发生 hash 冲突后保存的下一个 IndexItem 的位置。

Slot Table 中每个 hash 槽存放的是 IndexItem 在 Index Linked List 的位置,如果 hash 冲突时,新的 IndexItem 插入链表头, 它的 Next Index Offset 中存放之前链表头 IndexItem 位置,同时覆盖 Slot Table 中的 hash 槽为最新 IndexItem 位置。代码如下:

//org.apache.rocketmq.store.index.IndexFile::putKey
public boolean putKey(final String key, final long phyOffset, final long storeTimestamp) {
    int keyHash = indexKeyHashMethod(key);
    int slotPos = keyHash % this.hashSlotNum;
    int absSlotPos = IndexHeader.INDEX_HEADER_SIZE + slotPos * hashSlotSize;
    ...
    //从 Slot Table 获取当前最新消息位置
    int slotValue = this.mappedByteBuffer.getInt(absSlotPos);
    ...
    int absIndexPos =
        IndexHeader.INDEX_HEADER_SIZE + this.hashSlotNum * hashSlotSize
            + this.indexHeader.getIndexCount() * indexSize;
 
    this.mappedByteBuffer.putInt(absIndexPos, keyHash);
    this.mappedByteBuffer.putLong(absIndexPos + 4, phyOffset);
    this.mappedByteBuffer.putInt(absIndexPos + 4 + 8, (int) timeDiff);
    //存放之前链表头 IndexItem 位置
    this.mappedByteBuffer.putInt(absIndexPos + 4 + 8 + 4, slotValue);
    //更新 Slot Table 中 hash 槽的值为最新消息位置
    this.mappedByteBuffer.putInt(absSlotPos, this.indexHeader.getIndexCount());
 
    if (this.indexHeader.getIndexCount() <= 1) {
        this.indexHeader.setBeginPhyOffset(phyOffset);
        this.indexHeader.setBeginTimestamp(storeTimestamp);
    }
 
    if (invalidIndex == slotValue) {
        this.indexHeader.incHashSlotCount();
    }
    this.indexHeader.incIndexCount();
    this.indexHeader.setEndPhyOffset(phyOffset);
    this.indexHeader.setEndTimestamp(storeTimestamp);
 
    return true;
    ...
}

综上所述一个完整的消息写入流程包括:同步写入 Commitlog 文件缓存区,异步构建 ConsumeQueue、IndexFile 文件。

3.3 消息刷盘

RocketMQ 消息刷盘主要分为同步刷盘和异步刷盘。

(1) 同步刷盘:只有在消息真正持久化至磁盘后 RocketMQ 的 Broker 端才会真正返回给 Producer 端一个成功的 ACK 响应。同步刷盘对 MQ 消息可靠性来说是一种不错的保障,但是性能上会有较大影响,一般金融业务使用该模式较多。

(2) 异步刷盘:能够充分利用 OS 的 Page Cache 的优势,只要消息写入 Page Cache 即可将成功的 ACK 返回给 Producer 端。消息刷盘采用后台异步线程提交的方式进行,降低了读写延迟,提高了 MQ 的性能和吞吐量。异步刷盘包含开启堆外内存和未开启堆外内存两种方式。

在 CommitLog 中提交刷盘请求时,会根据当前 Broker 相关配置决定是同步刷盘还是异步刷盘。

//org.apache.rocketmq.store.CommitLog::submitFlushRequest
public CompletableFuture<PutMessageStatus> submitFlushRequest(AppendMessageResult result, MessageExt messageExt) {
    //同步刷盘
    if (FlushDiskType.SYNC_FLUSH == this.defaultMessageStore.getMessageStoreConfig().getFlushDiskType()) {
        final GroupCommitService service = (GroupCommitService) this.flushCommitLogService;
        if (messageExt.isWaitStoreMsgOK()) {
            GroupCommitRequest request = new GroupCommitRequest(result.getWroteOffset() + result.getWroteBytes(),
                    this.defaultMessageStore.getMessageStoreConfig().getSyncFlushTimeout());
            service.putRequest(request);
            return request.future();
        } else {
            service.wakeup();
            return CompletableFuture.completedFuture(PutMessageStatus.PUT_OK);
        }
    }
    //异步刷盘
    else {
        if (!this.defaultMessageStore.getMessageStoreConfig().isTransientStorePoolEnable()) {
            flushCommitLogService.wakeup();
        } else  {
            //开启堆外内存的异步刷盘
            commitLogService.wakeup();
        }
        return CompletableFuture.completedFuture(PutMessageStatus.PUT_OK);
    }
}

GroupCommitService、FlushRealTimeService、CommitRealTimeService 三者继承关系如图;

GroupCommitService:同步刷盘线程。如下图所示,消息写入到 Page Cache 后通过 GroupCommitService 同步刷盘,消息处理线程阻塞等待刷盘结果。

//org.apache.rocketmq.store.CommitLog.GroupCommitService::run
public void run() {
    ...
    while (!this.isStopped()) {
        this.waitForRunning(10);
        this.doCommit();
    }
    ...
}
 
//org.apache.rocketmq.store.CommitLog.GroupCommitService::doCommit
private void doCommit() {
    ...
    for (GroupCommitRequest req : this.requestsRead) {
        boolean flushOK = CommitLog.this.mappedFileQueue.getFlushedWhere() >= req.getNextOffset();
        for (int i = 0; i < 2 && !flushOK; i++) {
            CommitLog.this.mappedFileQueue.flush(0);
            flushOK = CommitLog.this.mappedFileQueue.getFlushedWhere() >= req.getNextOffset();
        }
        //唤醒等待刷盘完成的消息处理线程
        req.wakeupCustomer(flushOK ? PutMessageStatus.PUT_OK : PutMessageStatus.FLUSH_DISK_TIMEOUT);
    }
    ...
}
 
//org.apache.rocketmq.store.MappedFile::flush
public int flush(final int flushLeastPages) {
    if (this.isAbleToFlush(flushLeastPages)) {
        ...
        //使用到了 writeBuffer 或者 fileChannel 的 position 不为 0 时用 fileChannel 进行强制刷盘
        if (writeBuffer != null || this.fileChannel.position() != 0) {
            this.fileChannel.force(false);
        } else {
            //使用 MappedByteBuffer 进行强制刷盘
            this.mappedByteBuffer.force();
        }
        ...
    }
}

FlushRealTimeService:未开启堆外内存的异步刷盘线程。如下图所示,消息写入到 Page Cache 后,消息处理线程立即返回,通过 FlushRealTimeService 异步刷盘。

//org.apache.rocketmq.store.CommitLog.FlushRealTimeService
public void run() {
    ...
    //判断是否需要周期性进行刷盘
    if (flushCommitLogTimed) {
        //固定休眠 interval 时间间隔
        Thread.sleep(interval);
    } else {
        // 如果被唤醒就刷盘,非周期性刷盘
        this.waitForRunning(interval);
    }
    ...
    // 这边和 GroupCommitService 用的是同一个强制刷盘方法
    CommitLog.this.mappedFileQueue.flush(flushPhysicQueueLeastPages);
    ...
}

CommitRealTimeService:开启堆外内存的异步刷盘线程。如下图所示,消息处理线程把消息写入到堆外内存后立即返回。后续先通过 CommitRealTimeService 把消息由堆外内存异步提交至 Page Cache,再由 FlushRealTimeService 线程异步刷盘。

注意:在消息异步提交至 Page Cache 后,业务就可以从 MappedByteBuffer 读取到该消息。

消息写入到堆外内存 writeBuffer 后,会通过 isAbleToCommit 方法判断是否积累到至少提交页数(默认4页)。如果页数达到最小提交页数,则批量提交;否则还是驻留在堆外内存,这边有丢失消息风险。通过这种批量操作,读和写的 Page Cahe 会间隔数页,降低了 Page Cahe 读写冲突的概率,实现了读写分离。具体实现逻辑如下:

//org.apache.rocketmq.store.CommitLog.CommitRealTimeService
class CommitRealTimeService extends FlushCommitLogService {
    @Override
    public void run() {
        while (!this.isStopped()) {
            ...
            int commitDataLeastPages = CommitLog.this.defaultMessageStore.getMessageStoreConfig().getCommitCommitLogLeastPages();
 
            ...
            //把消息 commit 到内存缓冲区,最终调用的是 MappedFile::commit0 方法,只有达到最少提交页数才能提交成功,否则还在堆外内存中
            boolean result = CommitLog.this.mappedFileQueue.commit(commitDataLeastPages);
            if (!result) {
                //唤醒 flushCommitLogService,进行强制刷盘
                flushCommitLogService.wakeup();
            }
            ...
            this.waitForRunning(interval);
        }
    }
}
 
//org.apache.rocketmq.store.MappedFile::commit0
protected void commit0() {
    int writePos = this.wrotePosition.get();
    int lastCommittedPosition = this.committedPosition.get();
     
    //消息提交至 Page Cache,并未实际刷盘
    if (writePos - lastCommittedPosition > 0) {
        ByteBuffer byteBuffer = writeBuffer.slice();
        byteBuffer.position(lastCommittedPosition);
        byteBuffer.limit(writePos);
        this.fileChannel.position(lastCommittedPosition);
        this.fileChannel.write(byteBuffer);
        this.committedPosition.set(writePos);
    }
}

下面总结一下三种刷盘机制的使用场景及优缺点。

四、消息读取

消息读取逻辑相比写入逻辑简单很多,下面着重分析下根据 offset 查询消息和根据 key 查询消息是如何实现的。

4.1 根据 offset 查询

读取消息的过程就是先从 ConsumeQueue 中找到消息在 CommitLog 的物理偏移地址,然后再从 CommitLog 文件中读取消息的实体内容。

//org.apache.rocketmq.store.DefaultMessageStore::getMessage
public GetMessageResult getMessage(final String group, final String topic, final int queueId, final long offset,
    final int maxMsgNums,
    final MessageFilter messageFilter) {
    long nextBeginOffset = offset;
 
    GetMessageResult getResult = new GetMessageResult();
 
    final long maxOffsetPy = this.commitLog.getMaxOffset();
    //找到对应的 ConsumeQueue
    ConsumeQueue consumeQueue = findConsumeQueue(topic, queueId);
    ...
    //根据 offset 找到对应的 ConsumeQueue 的 MappedFile
    SelectMappedBufferResult bufferConsumeQueue = consumeQueue.getIndexBuffer(offset);
    status = GetMessageStatus.NO_MATCHED_MESSAGE;
    long maxPhyOffsetPulling = 0;
 
    int i = 0;
    //能返回的最大信息大小,不能大于 16M
    final int maxFilterMessageCount = Math.max(16000, maxMsgNums * ConsumeQueue.CQ_STORE_UNIT_SIZE);
    for (; i < bufferConsumeQueue.getSize() && i < maxFilterMessageCount; i += ConsumeQueue.CQ_STORE_UNIT_SIZE) {
        //CommitLog 物理地址
        long offsetPy = bufferConsumeQueue.getByteBuffer().getLong();
        int sizePy = bufferConsumeQueue.getByteBuffer().getInt();
        maxPhyOffsetPulling = offsetPy;
        ...
        //根据 offset 和 size 从 CommitLog 拿到具体的 Message
        SelectMappedBufferResult selectResult = this.commitLog.getMessage(offsetPy, sizePy);
        ...
        //将 Message 放入结果集
        getResult.addMessage(selectResult);
        status = GetMessageStatus.FOUND;
    }
 
    //更新 offset
    nextBeginOffset = offset + (i / ConsumeQueue.CQ_STORE_UNIT_SIZE);
 
    long diff = maxOffsetPy - maxPhyOffsetPulling;
    long memory = (long) (StoreUtil.TOTAL_PHYSICAL_MEMORY_SIZE
        * (this.messageStoreConfig.getAccessMessageInMemoryMaxRatio() / 100.0));
    getResult.setSuggestPullingFromSlave(diff > memory);
    ...
    getResult.setStatus(status);
    getResult.setNextBeginOffset(nextBeginOffset);
    return getResult;
}

4.2 根据 key 查询

读取消息的过程就是用 topic 和 key 找到 IndexFile 索引文件中的一条记录,根据记录中的 CommitLog 的 offset 从 CommitLog 文件中读取消息的实体内容。

//org.apache.rocketmq.store.DefaultMessageStore::queryMessage
public QueryMessageResult queryMessage(String topic, String key, int maxNum, long begin, long end) {
    QueryMessageResult queryMessageResult = new QueryMessageResult();
    long lastQueryMsgTime = end;
     
    for (int i = 0; i < 3; i++) {
        //获取 IndexFile 索引文件中记录的消息在 CommitLog 文件物理偏移地址
        QueryOffsetResult queryOffsetResult = this.indexService.queryOffset(topic, key, maxNum, begin, lastQueryMsgTime);
        ...
        for (int m = 0; m < queryOffsetResult.getPhyOffsets().size(); m++) {
            long offset = queryOffsetResult.getPhyOffsets().get(m);
            ...
            MessageExt msg = this.lookMessageByOffset(offset);
            if (0 == m) {
                lastQueryMsgTime = msg.getStoreTimestamp();
            }
            ...
            //在 CommitLog 文件获取消息内容
            SelectMappedBufferResult result = this.commitLog.getData(offset, false);
            ...
            queryMessageResult.addMessage(result);
            ...
        }
    }
 
    return queryMessageResult;
}

在 IndexFile 索引文件,查找 CommitLog 文件物理偏移地址实现如下:

//org.apache.rocketmq.store.index.IndexFile::selectPhyOffset
public void selectPhyOffset(final List<Long> phyOffsets, final String key, final int maxNum,
final long begin, final long end, boolean lock) {
    int keyHash = indexKeyHashMethod(key);
    int slotPos = keyHash % this.hashSlotNum;
    int absSlotPos = IndexHeader.INDEX_HEADER_SIZE + slotPos * hashSlotSize;
    //获取相同 hash 值 key 的第一个 IndexItme 存储位置,即链表的首节点
    int slotValue = this.mappedByteBuffer.getInt(absSlotPos);
     
    //遍历链表节点
    for (int nextIndexToRead = slotValue; ; ) {
        if (phyOffsets.size() >= maxNum) {
            break;
        }
 
        int absIndexPos =
            IndexHeader.INDEX_HEADER_SIZE + this.hashSlotNum * hashSlotSize
                + nextIndexToRead * indexSize;
 
        int keyHashRead = this.mappedByteBuffer.getInt(absIndexPos);
        long phyOffsetRead = this.mappedByteBuffer.getLong(absIndexPos + 4);
 
        long timeDiff = (long) this.mappedByteBuffer.getInt(absIndexPos + 4 + 8);
        int prevIndexRead = this.mappedByteBuffer.getInt(absIndexPos + 4 + 8 + 4);
 
        if (timeDiff < 0) {
            break;
        }
 
        timeDiff *= 1000L;
 
        long timeRead = this.indexHeader.getBeginTimestamp() + timeDiff;
        boolean timeMatched = (timeRead >= begin) && (timeRead <= end);
 
        //符合条件的结果加入 phyOffsets
        if (keyHash == keyHashRead && timeMatched) {
            phyOffsets.add(phyOffsetRead);
        }
 
        if (prevIndexRead <= invalidIndex
            || prevIndexRead > this.indexHeader.getIndexCount()
            || prevIndexRead == nextIndexToRead || timeRead < begin) {
            break;
        }
         
        //继续遍历链表
        nextIndexToRead = prevIndexRead;
    }
    ...
}

五、总结

本文从源码的角度介绍了 RocketMQ 存储系统的核心模块实现,包括存储架构、消息写入和消息读取。

RocketMQ 把所有 Topic 下的消息都写入到 CommitLog 里面,实现了严格的顺序写。通过文件预热防止 Page Cache 被交换到 swap 空间,减少读写文件时缺页中断。使用 mmap 对 CommitLog 文件进行读写,将对文件的操作转化为直接对内存地址进行操作,从而极大地提高了文件的读写效率。

对于性能要求高、数据一致性要求不高的场景下,可以通过开启堆外内存,实现读写分离,提升磁盘的吞吐量。总之,存储模块的学习需要对操作系统原理有一定了解。作者采用的性能极致优化方案值得我们好好学习。

RocketMQ源码解析:从架构设计到消息队列实现 消息队列作为分布式系统核心组件,通过解耦生产消费实现异步通信。RocketMQ作为阿里开源的分布式消息中间件,采用发布/订阅模型,支持顺序消息和事务消息等特性。其核心架构包含NameServer、Broker和Client三大模块,通过Netty实现高性能网络通信。源码层面采用分层设计和模块化组织,包含路由管理、消息存储、负载均衡等关键技术。阅读RocketMQ源码不仅能深入理解消息队列工作原理,还能学习到高性能存储引擎设计、分布式系统一致性保证等工程实践。对于日均处理万亿级消息的系统,RocketMQ的顺 阅读详情

相关推荐

RocketMQ源码解析:从分布式消息队列到高性能存储设计

分布式消息队列是现代微服务架构的核心组件,通过解耦生产者和消费者实现系统间的异步通信。RocketMQ作为阿里巴巴开源的分布式消息中间件,其设计哲学融合了高性能存储引擎和轻量级协调服务等关键技术。从技术实现看,RocketMQ采用CommitLog顺序写盘与ConsumeQueue索引分离的存储架构,配合内存映射文件和批量刷盘等优化手段,可支持百万级TPS的消息吞吐。在分布式协调方面,其NameServer模块通过无状态设计和心跳机制实现服务注册发现,相比ZooKeeper等方案更加轻量化。本文以5.2.0

weixin_34221654的博客 249

RocketMQ源码分析(九)之AllocateMappedFileService

RocketMQ源码-AllocateMappedFileService分析

jannal专栏 583

手把手教你用CODESYS将旧笔记本改造成软PLC(含证书配置避坑指南)

本文提供了一份详尽的指南,教你如何利用CODESYS平台将闲置旧笔记本改造为一台功能完整的软PLC。内容涵盖从硬件评估、系统实时性优化、软件安装与驱动配置,到关键的证书授权管理避坑指南,旨在帮助自动化工程师和爱好者低成本搭建稳定可靠的学习与开发平台。

weixin_29190573的博客 293

RocketMq CommitLog 文件创建

要理解rocketMq broker CommitLog文件的创建就要了解AllocateMappedFileService的运行机制,本文从以下几个方面详细介绍mapped文件从提交请求到创建,再到刷盘三个步骤仔细介绍mapped文件的生成和数据刷盘。

weixin_41953346的博客 449

电机控制-PMSM无感FOC控制(五)SVPWM过调制策略优化与谐波抑制

本文深入探讨了PMSM无感FOC控制中的SVPWM过调制策略优化与谐波抑制。针对电机高速运行时电压利用率不足的问题,分析了过调制技术的必要性,并详细阐述了分区过调制、谐波注入及闭环优化等主流策略,旨在提升电压利用率与抑制电流谐波,实现电机高性能控制。

convnet3designer的博客 355

MOS管的安全工作区SOA详解(一)限制线介绍

一篇文章让你搞懂MOS管的SOA曲线!

qq_45508321的博客 1万+

AllocateMappedFileService源码分析

引言 创建MappedFile的类。 使用了生产者消费者模式创建文件。 使用了ConcurrentHashMap put是否 因为单个文件大小为1G,所有使用一个消费者创建mappedFile较为合适 类图 主要属性 private static final InternalLogger log = InternalLoggerFactory.getLogger(LoggerName.STORE...

cjdjcdj的博客 707

闲人闲谈PS之一项目库存跨公司业务STO解决方案--SAP闲人的开篇

写这篇文章之前,简单说一下发这篇文章的动机。也算是在SAP这一行干了快10多年,在对一个模块了解越来越深入,越发觉自己的SAP知识浅薄。总的来说,和多数顾问一样,对于**标准功能**的应用业务场景理解还是存在或多或少的知识盲区。 因为一个偶然,看到SAP团子君的文章,分享了很多干货文章。这也是自己一直想做的时候,不管水平高低与否,分享本身就意味着提升。好了废话不多说,先在CSDN上发一篇吧,困惑自己将近10年的问题的解决方案。 业务场景:在项目型企业中,通常会有这样的业务,母公司和客...

SAP闲人的博客 9276

阿里二面:RockeMQ 是如何通过 mmap 大幅提升单机吞吐量的?

点击关注公众号,实用技术文章及时了解今天抽空给大家整理了一份关于RocketMQ的高性能知识点文章总结。希望能对各位读者有所帮助。关于RockeMQ的基本介绍简介RocketMQ是一个纯Java、分布式、队列模型的开源消息中间件,前身是MetaQ,是阿里参考Kafka特点研发的一个队列模型的消息中间件,后开源给apache基金会成为了apache顶级开源项目,具有高性能、高可靠、高实时、分布式特点...

Java知音 818

Silly Tavern酒馆ai角色卡与世界书导入超详细教程!

前几天,我在设置 Silly Tavern 的时候,想导入一个喜欢的角色卡,结果发现不少朋友其实已经下载好了角色资源,但却不知道怎么正确导入使用。这篇文章就作为一份完整的新手向教程,一步步教你如何在 Silly Tavern 中导入角色卡、世界书,并实现与 AI 角色的真实互动。如果你是第一次接触这个功能,建议先收藏慢慢看~点击菜单栏上的 图标,打开角色界面。初始状态下,你应该只看到默认角色 Seraphina。你可以先点击她的头像尝试聊天,也可以导入自己喜欢的角色。点击导入按钮,选择你下载好的角色卡(通

代码简单说 Vue、JAVA、PHP、Node.js 熟练运用,接口、架构、性能全搞定。 2万+

论文阅读-Whisper语音识别(OpenAI)

Whisper 是一个自动语音识别(ASR,Automatic Speech Recognition)系统,OpenAI 通过从网络上收集了 68 万小时的多语言,其中11万小时覆盖96 种语言,12万小时的语言标号为英语,用多任务(multitask)监督数据对 Whisper 进行了训练。

一位不是很硕的鉴伪方向硕士 6375

RocketMQ 源码解析:核心模块底层实现

本文深入剖析了RocketMQ消息发送与存储两大核心模块的实现机制。在消息发送方面,详细解析了生产者初始化、路由发现、负载均衡算法及同步/异步发送流程;在消息存储方面,重点介绍了Broker的存储架构、消息持久化机制与高性能写入优化。通过源码层面的分析,揭示了RocketMQ实现高吞吐、低延迟、高可靠性的底层设计原理,为开发者深入理解和使用RocketMQ提供了技术参考。

码路同行 834

滤波算法实现大全——基于匀速直线运动模型的kalman滤波算法

滤波算法实现大全——基于匀速直线运动模型的kalman滤波算法

jane0819的博客 529

39.RocketMQ高性能核心原理与源码架构剖析

​ 从之前Producer发送消息的过程以及Conmer拉取消息的过程,我们可以抽象出RocketMQ中一个消息分配的管理模型。这个模型是我们在使用RocketMQ时,很重要的进行性能优化的依据。

Csdn_xzh的博客 1699

15、 深入理解Akka微服务:创建与管理体育博彩平台

本博文深入探讨了如何使用Akka微服务架构为体育博彩平台创建投影和管理事件数据,包括市场投影、投注投影以及数据库投影的实现。同时,介绍了通过gRPC提供HTTP端点以供外部系统访问的方法,并详细说明了在本地环境和Kubernetes中运行应用程序的步骤及配置建议。

weixin_35756624的博客 100

IMSL CNL 7.0.0 (x86-64)Crack

IMSL CNL 7.0.0 (x86-64)Crack intel的算法库破解文件,这是C++版本的破解文件

RocketMQ高性能核心原理与源码架构剖析

但是在测试源码中,需要指定NameServer地址。​ 调试时,先在项目目录下创建一个conf目录,并从distribution拷贝broker.conf和logback_broker.xml和logback_namesrv.xml。启动example模块下的org.apache.rocketmq.example.quickstart.Producer类即可发送消息。启动Broker时,同样需要ROCETMQ_HOME环境变量,并且还需要配置一个-c 参数,指向broker.conf配置文件。

不积跬步无以至千里 804

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

3-RocketMQ高性能核心原理与源码架构剖析

​ 从之前Producer发送消息的过程以及Conmer拉取消息的过程,我们可以抽象出RocketMQ中一个消息分配的管理模型。这个模型是我们在使用RocketMQ时,很重要的进行性能优化的依据。

qq_38132995的博客 879

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

RocketMQ核心源码深度解读:架构原理与核心机制剖析

本文基于RocketMQ 5.3.0版本源码,深入解析其高吞吐、高可用、高性能的设计原理。首先介绍了源码环境搭建方法,包括核心模块功能和编译启动流程。随后分析了NameServer和Broker的启动过程,重点剖析了基于Netty的远程调用框架、Broker心跳注册机制。在核心业务流程方面,详细解读了生产者消息发送和消费者消息拉取的实现逻辑,包括负载均衡策略和消费模式差异。最后深入探讨了消息持久化设计,包括CommitLog、ConsumeQueue等文件结构,以及顺序写、刷盘策略等关键机制,帮助开发者从使

慢慢 489

RocketMQ核心源码深度解析:从启动流程到高性能设计

《RocketMQ源码解析与核心设计》摘要:本文系统剖析了RocketMQ的源码架构与实现原理。从环境搭建到核心流程,详细解读了NameServer注册中心、Broker消息代理的启动机制,深入分析了Netty通信框架、消息持久化设计(CommitLog顺序写+索引分离)、主从复制等关键技术。重点探讨了延迟消息的时间轮算法、长轮询机制等高级特性,以及零拷贝、顺序写等性能优化手段。通过源码阅读揭示了RocketMQ简洁高效、可扩展的设计理念,包括轻量级服务注册、读写双Buffer等优秀实践

alonewolf_99的博客 629

RocketMQ核心知识点与面试高频问题解析

分布式消息中间件是现代高并发系统的关键组件,通过解耦生产者和消费者实现系统弹性扩展。RocketMQ作为阿里开源的标杆产品,其核心架构采用NameServer注册中心与Broker集群的分布式设计,支持十万级TPS的消息吞吐。在消息可靠性方面,通过同步双写、事务消息二阶段提交等机制保障数据一致性,特别适用于电商交易、金融支付等场景。本文深入解析CommitLog存储机制、消费者负载均衡策略等15个面试高频考点,包含线上调优参数配置和典型问题解决方案,帮助开发者掌握RocketMQ在分布式系统中的工程实践。

axfcjwkbi259888707的博客 280

如何阅读阿里系的开源作品的源码

&nbsp;&nbsp;&nbsp;&nbsp;从大四开始,一直保持着阅读源码的习惯,也一直都从事中间件相关领域的产品开发,对于如何阅读源码和如何快速选型也有自己的心得于体会。 &nbsp;&nbsp;&nbsp;&nbsp;下面着重讲讲如何阅读 RocketMQ 的源码。 首先,我们需要知道 RocketMQ 是啥东西?消息中间件,仅仅是这样还不够的呢?阿里很多中间件产品都有自己的概念,我...

煎蛋的梦 778

Java后端面试核心:限流、负载均衡与消息队列实战解析

限流算法是保障系统稳定性的关键技术,通过计数器、滑动窗口、漏桶和令牌桶等算法控制请求流量。其核心原理是在单位时间内限制请求数量,防止系统过载。在分布式系统中,结合Redis和Lua脚本可实现集群限流,解决单机限流的瓶颈问题。负载均衡技术则通过轮询、加权、最少连接等算法分配请求,提升系统吞吐量。消息队列通过解耦生产者和消费者,实现异步处理与削峰填谷。本文结合美团等大厂真实面试题,深入讲解这些技术的工程实现与优化策略,帮助开发者掌握高并发系统设计要点。

weixin_33910460的博客 459
上一篇: 超详细讲解页面加载过程
下一篇: Innodb到底是怎么加锁的
在酒吧写代码
博客等级 码龄7年 214粉丝 330原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址