RocketMQ 源码解析—Broker 消息存储

MQ - RocketMQ底层原理和源码解析 RocketMQ底层原理和源码解析 本文的内容主要包括:MQ的对比和选型、RocketMQ原理、RocketMQ源码解析、事务消息。 Rocketmq性能压测客户端:https://github.com/Force-King/rocketmq-test 一、MQ的对比和选型 目前业界主要的消息中间件有:ActiveMQ、RabbitMQ、ZeroMQ、Kafka、MetaMQ、RocketMQ。其中开源的,社区比较活跃的是ActiveMQ、RabbitMQ、Kafka、RocketMQ。所以,我们做技术选型 阅读详情

阅读须知

  • 文章中使用/* */注释的方法会做深入分析

正文

在前面分析的 Broker 处理 client 发送请求流程中,我们看到了 Broker 会存放来自 client 的消息,DefaultMessageStore 是 Broker 消息存储用到的最关键的一个类,我们先来看下 DefaultMessageStore 的成员变量:

// 消息存储配置
private final MessageStoreConfig messageStoreConfig;
// CommitLog 文件的存储实现类
private final CommitLog commitLog;
// 消息队列存储缓存表,按 topic 分组,每个 topic 对应多个队列
private final ConcurrentMap<String/* topic */, ConcurrentMap<Integer/* queueId */, ConsumeQueue>> consumeQueueTable;
// 消息队列文件 ConsumeQueue 刷盘服务
private final FlushConsumeQueueService flushConsumeQueueService;
// 清除 CommitLog 文件服务
private final CleanCommitLogService cleanCommitLogService;
// 清除 ConsumeQueue 文件服务
private final CleanConsumeQueueService cleanConsumeQueueService;
// 索引文件实现类
private final IndexService indexService;
// MappedFile 分配服务
private final AllocateMappedFileService allocateMappedFileService;
// CommitLog 消息分发,根据 CommitLog 文件构建 ConsumeQueue、IndexFile 文件
private final ReputMessageService reputMessageService;
// 存储高可用机制
private final HAService haService;

private final ScheduleMessageService scheduleMessageService;

private final StoreStatsService storeStatsService;

private final TransientStorePool transientStorePool;

private final RunningFlags runningFlags = new RunningFlags();
private final SystemClock systemClock = new SystemClock();

private final ScheduledExecutorService scheduledExecutorService =
    Executors.newSingleThreadScheduledExecutor(new ThreadFactoryImpl("StoreScheduledThread"));
private final BrokerStatsManager brokerStatsManager;
private final MessageArrivingListener messageArrivingListener;
private final BrokerConfig brokerConfig;

private volatile boolean shutdown = true;

private StoreCheckpoint storeCheckpoint;

private AtomicLong printTimes = new AtomicLong(0);

private final LinkedList<CommitLogDispatcher> dispatcherList;

private RandomAccessFile lockFile;

private FileLock lock;

boolean shutDownNormal = false;

DefaultMessageStore:

public PutMessageResult putMessage(MessageExtBrokerInner msg) {
	// 校验消息存储是否已经停止
    if (this.shutdown) {
        log.warn("message store has shutdown, so putMessage is forbidden");
        return new PutMessageResult(PutMessageStatus.SERVICE_NOT_AVAILABLE, null);
    }
    // 校验 broker 是否是 slave 模式
    if (BrokerRole.SLAVE == this.messageStoreConfig.getBrokerRole()) {
        long value = this.printTimes.getAndIncrement();
        if ((value % 50000) == 0) {
            log.warn("message store is slave mode, so putMessage is forbidden ");
        }
        return new PutMessageResult(PutMessageStatus.SERVICE_NOT_AVAILABLE, null);
    }
    // 校验消息存储是否可写
    if (!this.runningFlags.isWriteable()) {
        long value = this.printTimes.getAndIncrement();
        if ((value % 50000) == 0) {
            log.warn("message store is not writeable, so putMessage is forbidden " + this.runningFlags.getFlagBits());
        }
        return new PutMessageResult(PutMessageStatus.SERVICE_NOT_AVAILABLE, null);
    } else {
        this.printTimes.set(0);
    }
    // 校验 topic 的长度
    if (msg.getTopic().length() > Byte.MAX_VALUE) {
        log.warn("putMessage message topic length too long " + msg.getTopic().length());
        return new PutMessageResult(PutMessageStatus.MESSAGE_ILLEGAL, null);
    }
    // 校验属性字符串的长度
    if (msg.getPropertiesString() != null && msg.getPropertiesString().length() > Short.MAX_VALUE) {
        log.warn("putMessage message properties length too long " + msg.getPropertiesString().length());
        return new PutMessageResult(PutMessageStatus.PROPERTIES_SIZE_EXCEEDED, null);
    }
    // 校验操作系统页缓存是否繁忙
    if (this.isOSPageCacheBusy()) {
        return new PutMessageResult(PutMessageStatus.OS_PAGECACHE_BUSY, null);
    }
    long beginTime = this.getSystemClock().now();
    /* 存储 commit log */
    PutMessageResult result = this.commitLog.putMessage(msg);
    // 计算存储花费的时间
    long eclipseTime = this.getSystemClock().now() - beginTime;
    if (eclipseTime > 500) {
        log.warn("putMessage not in lock eclipse time(ms)={}, bodyLength={}", eclipseTime, msg.getBody().length);
    }
    this.storeStatsService.setPutMessageEntireTimeMax(eclipseTime);
    if (null == result || !result.isOk()) {
    	// 如果存储失败则增加存储失败的次数
        this.storeStatsService.getPutMessageFailedTimes().incrementAndGet();
    }
    return result;
}

CommitLog:

public PutMessageResult putMessage(final MessageExtBrokerInner msg) {
	// 设置存储时间
    msg.setStoreTimestamp(System.currentTimeMillis());
    // 设置消息体 CRC 校验和
    msg.setBodyCRC(UtilAll.crc32(msg.getBody()));
    AppendMessageResult result = null;
    StoreStatsService storeStatsService = this.defaultMessageStore.getStoreStatsService();
    String topic = msg.getTopic();
    int queueId = msg.getQueueId();
    // 获取消息事务类型
    final int tranType = MessageSysFlag.getTransactionValue(msg.getSysFlag());
    // TRANSACTION_NOT_TYPE 为普通消息、TRANSACTION_COMMIT_TYPE 为事务消息提交类型
    if (tranType == MessageSysFlag.TRANSACTION_NOT_TYPE
        || tranType == MessageSysFlag.TRANSACTION_COMMIT_TYPE) {
        // 获取延迟发送级别
        if (msg.getDelayTimeLevel() > 0) {
        	// 判断如果延迟发送级别是否超过了最大延迟发送级别(默认为18),则将延迟发送级别设置为默认的最大延迟发送级别
            if (msg.getDelayTimeLevel() > this.defaultMessageStore.getScheduleMessageService().getMaxDelayLevel()) {
                msg.setDelayTimeLevel(this.defaultMessageStore.getScheduleMessageService().getMaxDelayLevel());
            }
            // 设置延迟发送的 topic
            topic = ScheduleMessageService.SCHEDULE_TOPIC;
            // 根据延迟发送级别确定队列 id
            queueId = ScheduleMessageService.delayLevel2QueueId(msg.getDelayTimeLevel());
            // 备份真正的 topic 和队列 id
            MessageAccessor.putProperty(msg, MessageConst.PROPERTY_REAL_TOPIC, msg.getTopic());
            MessageAccessor.putProperty(msg, MessageConst.PROPERTY_REAL_QUEUE_ID, String.valueOf(msg.getQueueId()));
            msg.setPropertiesString(MessageDecoder.messageProperties2String(msg.getProperties()));
            msg.setTopic(topic);
            msg.setQueueId(queueId);
        }
    }
    long eclipseTimeInLock = 0;
    MappedFile unlockMappedFile = null;
    /* 获取 commit log 最新的一个文件 */
    MappedFile mappedFile = this.mappedFileQueue.getLastMappedFile();
    // 写消息前加锁,写消息是串行的
    putMessageLock.lock();
    try {
        long beginLockTimestamp = this.defaultMessageStore.getSystemClock().now();
        this.beginTimeInLock = beginLockTimestamp;
        // 这里的设置存储时间戳,以确保全局有序
        msg.setStoreTimestamp(beginLockTimestamp);
        /* 如果文件不存在或者已满,则创建新文件 */
        if (null == mappedFile || mappedFile.isFull()) {
            mappedFile = this.mappedFileQueue.getLastMappedFile(0);
        }
        if (null == mappedFile) {
            log.error("create mapped file1 error, topic: " + msg.getTopic() + " clientAddr: " + msg.getBornHostString());
            beginTimeInLock = 0;
            return new PutMessageResult(PutMessageStatus.CREATE_MAPEDFILE_FAILED, null);
        }
        /* 追加消息 */
        result = mappedFile.appendMessage(msg, this.appendMessageCallback);
        switch (result.getStatus()) {
            case PUT_OK:
                break;
            // 如果已经到了文件的结尾,则创建新的文件重新写入
            case END_OF_FILE:
                unlockMappedFile = mappedFile;
                mappedFile = this.mappedFileQueue.getLastMappedFile(0);
                if (null == mappedFile) {
                    log.error("create mapped file2 error, topic: " + msg.getTopic() + " clientAddr: " + msg.getBornHostString());
                    beginTimeInLock = 0;
                    return new PutMessageResult(PutMessageStatus.CREATE_MAPEDFILE_FAILED, result);
                }
                result = mappedFile.appendMessage(msg, this.appendMessageCallback);
                break;
            // 下面为存放失败的结果返回
            case MESSAGE_SIZE_EXCEEDED:
            case PROPERTIES_SIZE_EXCEEDED:
                beginTimeInLock = 0;
                return new PutMessageResult(PutMessageStatus.MESSAGE_ILLEGAL, result);
            case UNKNOWN_ERROR:
                beginTimeInLock = 0;
                return new PutMessageResult(PutMessageStatus.UNKNOWN_ERROR, result);
            default:
                beginTimeInLock = 0;
                return new PutMessageResult(PutMessageStatus.UNKNOWN_ERROR, result);
        }
        // 计算存放消息消耗的时间
        eclipseTimeInLock = this.defaultMessageStore.getSystemClock().now() - beginLockTimestamp;
        beginTimeInLock = 0;
    } finally {
        putMessageLock.unlock();
    }
    if (eclipseTimeInLock > 500) {
        log.warn("[NOTIFYME]putMessage in lock cost time(ms)={}, bodyLength={} AppendMessageResult={}", eclipseTimeInLock, msg.getBody().length, result);
    }
    if (null != unlockMappedFile && this.defaultMessageStore.getMessageStoreConfig().isWarmMapedFileEnable()) {
        this.defaultMessageStore.unlockMappedFile(unlockMappedFile);
    }
    PutMessageResult putMessageResult = new PutMessageResult(PutMessageStatus.PUT_OK, result);
    // 统计存放消息的数量和总大小
    storeStatsService.getSinglePutMessageTopicTimesTotal(msg.getTopic()).incrementAndGet();
    storeStatsService.getSinglePutMessageTopicSizeTotal(topic).addAndGet(result.getWroteBytes());
    // 处理磁盘刷新
    handleDiskFlush(result, putMessageResult, msg);
    // 处理高可用
    handleHA(result, putMessageResult, msg);
    return putMessageResult;
}

这里会涉及到Broker “HA高可用”和“消息刷盘”的相关内容,我们会用单独的文章进行分析。
MappedFileQueue:

public MappedFile getLastMappedFile() {
    MappedFile mappedFileLast = null;
    while (!this.mappedFiles.isEmpty()) {
        try {
        	// 获取 MappedFile 集合中最后一个下标的元素,就是最后一个 MappedFile
            mappedFileLast = this.mappedFiles.get(this.mappedFiles.size() - 1);
            break;
        } catch (IndexOutOfBoundsException e) {
            // continue;
        } catch (Exception e) {
            log.error("getLastMappedFile has exception.", e);
            break;
        }
    }
    return mappedFileLast;
}

这里 mappedFiles 集合的内容是什么时候设置的呢?我们在分析 Broker 初始化流程时,在 BrokerController 的 initialize 方法中,调用了 DefaultMessageStore 的 load 方法来加载消息存储,这里会调用 CommitLog 的 load 方法来加载 commit log,而 mappedFiles 也就是在这里添加的了,所以它的内容就是 commitlog 目录下的所有文件。
MappedFileQueue:

public MappedFile getLastMappedFile(final long startOffset) {
    return getLastMappedFile(startOffset, true);
}

MappedFileQueue:

public MappedFile getLastMappedFile(final long startOffset, boolean needCreate) {
    long createOffset = -1;
    // 获取最新文件
    MappedFile mappedFileLast = getLastMappedFile();
    // 在最新文件为空或者已满时计算创建文件的偏移量
    if (mappedFileLast == null) {
        createOffset = startOffset - (startOffset % this.mappedFileSize);
    }
    if (mappedFileLast != null && mappedFileLast.isFull()) {
        createOffset = mappedFileLast.getFileFromOffset() + this.mappedFileSize;
    }
    if (createOffset != -1 && needCreate) {
    	// 设置一个最小20位的文件名
        String nextFilePath = this.storePath + File.separator + UtilAll.offset2FileName(createOffset);
        String nextNextFilePath = this.storePath + File.separator
            + UtilAll.offset2FileName(createOffset + this.mappedFileSize);
        MappedFile mappedFile = null;
        if (this.allocateMappedFileService != null) {
        	/* 存放请求并返回新建的 MappedFile */
            mappedFile = this.allocateMappedFileService.putRequestAndReturnMappedFile(nextFilePath,
                nextNextFilePath, this.mappedFileSize);
        } else {
            try {
                mappedFile = new MappedFile(nextFilePath, this.mappedFileSize);
            } catch (IOException e) {
                log.error("create mappedFile exception", e);
            }
        }
        if (mappedFile != null) {
            if (this.mappedFiles.isEmpty()) {
            	// 如果集合中还没有 MappedFile 对象,则将本次创建的 MappedFile 对象标记为队列中第一个创建的文件
                mappedFile.setFirstCreateInQueue(true);
            }
            this.mappedFiles.add(mappedFile);
        }
        return mappedFile;
    }
    return mappedFileLast;
}

AllocateMappedFileService:

public MappedFile putRequestAndReturnMappedFile(String nextFilePath, String nextNextFilePath, int fileSize) {
    int canSubmitRequests = 2;
    if (this.messageStore.getMessageStoreConfig().isTransientStorePoolEnable()) {
    	// 如果 broker 是 slave 模式,那么即使池中没有缓冲区,也不要快速失败
        if (this.messageStore.getMessageStoreConfig().isFastFailIfNoBufferInStorePool()
            && BrokerRole.SLAVE != this.messageStore.getMessageStoreConfig().getBrokerRole()) {
            canSubmitRequests = this.messageStore.getTransientStorePool().remainBufferNumbs() - this.requestQueue.size();
        }
    }
    AllocateRequest nextReq = new AllocateRequest(nextFilePath, fileSize);
    // 将分配请求放入请求表
    boolean nextPutOK = this.requestTable.putIfAbsent(nextFilePath, nextReq) == null;
    if (nextPutOK) {
    	// 如果缓冲区不足,则创建文件失败,移除此请求并返回
        if (canSubmitRequests <= 0) {
            log.warn("[NOTIFYME]TransientStorePool is not enough, so create mapped file error, " +
                "RequestQueueSize : {}, StorePoolSize: {}", this.requestQueue.size(), this.messageStore.getTransientStorePool().remainBufferNumbs());
            this.requestTable.remove(nextFilePath);
            return null;
        }
        // 将请求放入请求队列
        boolean offerOK = this.requestQueue.offer(nextReq);
        if (!offerOK) {
            log.warn("never expected here, add a request to preallocate queue failed");
        }
        canSubmitRequests--;
    }
    AllocateRequest nextNextReq = new AllocateRequest(nextNextFilePath, fileSize);
    boolean nextNextPutOK = this.requestTable.putIfAbsent(nextNextFilePath, nextNextReq) == null;
    if (nextNextPutOK) {
        if (canSubmitRequests <= 0) {
            log.warn("[NOTIFYME]TransientStorePool is not enough, so skip preallocate mapped file, " +
                "RequestQueueSize : {}, StorePoolSize: {}", this.requestQueue.size(), this.messageStore.getTransientStorePool().remainBufferNumbs());
            this.requestTable.remove(nextNextFilePath);
        } else {
            boolean offerOK = this.requestQueue.offer(nextNextReq);
            if (!offerOK) {
                log.warn("never expected here, add a request to preallocate queue failed");
            }
        }
    }
    if (hasException) {
        log.warn(this.getServiceName() + " service has exception. so return null");
        return null;
    }
    AllocateRequest result = this.requestTable.get(nextFilePath);
    try {
        if (result != null) {
        	// 请求结果闭锁,超时时间5s
            boolean waitOK = result.getCountDownLatch().await(waitTimeOut, TimeUnit.MILLISECONDS);
            if (!waitOK) {
                log.warn("create mmap timeout " + result.getFilePath() + " " + result.getFileSize());
                return null;
            } else {
            	// 如果请求闭锁失败,则移除此请求
                this.requestTable.remove(nextFilePath);
                return result.getMappedFile();
            }
        } else {
            log.error("find preallocate mmap failed, this never happen");
        }
    } catch (InterruptedException e) {
        log.warn(this.getServiceName() + " service has exception. ", e);
    }
    return null;
}

这里我们只看到请求放入队列,并没有看到请求的处理过程,AllocateMappedFileService 继承了 ServiceThread,所以我们可以把它理解为一个线程任务,请求的处理也就是在 run 方法中,而线程的启动则是在 BrokerController 的初始化过程,在消息存储对象 DefaultMessageStore 时,DefaultMessageStore 的构造方法中启动了 AllocateMappedFileService 中维护的线程。
AllocateMappedFileService:

public void run() {
    log.info(this.getServiceName() + " service started");
    /* 循环做内存映射文件操作 */
    while (!this.isStopped() && this.mmapOperation()) {
    }
    log.info(this.getServiceName() + " service end");
}

AllocateMappedFileService:

private boolean mmapOperation() {
    boolean isSuccess = false;
    AllocateRequest req = null;
    try {
    	// 从队列中读取请求,如果队列中没有请求则阻塞在这里
        req = this.requestQueue.take();
        AllocateRequest expectedRequest = this.requestTable.get(req.getFilePath());
        if (null == expectedRequest) {
            log.warn("this mmap request expired, maybe cause timeout " + req.getFilePath() + " "
                + req.getFileSize());
            return true;
        }
        if (expectedRequest != req) {
            log.warn("never expected here,  maybe cause timeout " + req.getFilePath() + " "
                + req.getFileSize() + ", req:" + req + ", expectedRequest:" + expectedRequest);
            return true;
        }
        if (req.getMappedFile() == null) {
            long beginTime = System.currentTimeMillis();
            MappedFile mappedFile;
            // 根据是否启用了临时存储池来初始化 MappedFile,MappedFile 初始化的主要动作就是创建 File,并打开 File 的 FileChannel
            if (messageStore.getMessageStoreConfig().isTransientStorePoolEnable()) {
                try {
                    mappedFile = ServiceLoader.load(MappedFile.class).iterator().next();
                    mappedFile.init(req.getFilePath(), req.getFileSize(), messageStore.getTransientStorePool());
                } catch (RuntimeException e) {
                    log.warn("Use default implementation.");
                    mappedFile = new MappedFile(req.getFilePath(), req.getFileSize(), messageStore.getTransientStorePool());
                }
            } else {
                mappedFile = new MappedFile(req.getFilePath(), req.getFileSize());
            }
            long eclipseTime = UtilAll.computeEclipseTimeMilliseconds(beginTime);
            if (eclipseTime > 10) {
                int queueSize = this.requestQueue.size();
                log.warn("create mappedFile spent time(ms) " + eclipseTime + " queue size " + queueSize
                    + " " + req.getFilePath() + " " + req.getFileSize());
            }
            // 判断是否启用预写 MappedFile
            if (mappedFile.getFileSize() >= this.messageStore.getMessageStoreConfig()
                .getMapedFileSizeCommitLog()
                &&
                this.messageStore.getMessageStoreConfig().isWarmMapedFileEnable()) {
                /* 预热 MappedFile */
                mappedFile.warmMappedFile(this.messageStore.getMessageStoreConfig().getFlushDiskType(),
                    this.messageStore.getMessageStoreConfig().getFlushLeastPagesWhenWarmMapedFile());
            }
            req.setMappedFile(mappedFile);
            this.hasException = false;
            isSuccess = true;
        }
    } catch (InterruptedException e) {
        log.warn(this.getServiceName() + " interrupted, possibly by shutdown.");
        this.hasException = true;
        return false;
    } catch (IOException e) {
        log.warn(this.getServiceName() + " service has exception. ", e);
        this.hasException = true;
        if (null != req) {
        	// 异常重新把请求放回队列
            requestQueue.offer(req);
            try {
                Thread.sleep(1);
            } catch (InterruptedException ignored) {
            }
        }
    } finally {
        if (req != null && isSuccess)
        	// 递减请求的闭锁值
            req.getCountDownLatch().countDown();
    }
    return true;
}

MappedFile:

public void warmMappedFile(FlushDiskType type, int pages) {
    long beginTime = System.currentTimeMillis();
    // 创建一个共享此缓冲区内容的新字节缓冲区
    ByteBuffer byteBuffer = this.mappedByteBuffer.slice();
    int flush = 0;
    long time = System.currentTimeMillis();
    for (int i = 0, j = 0; i < this.fileSize; i += MappedFile.OS_PAGE_SIZE, j++) {
    	// 0占位
        byteBuffer.put(i, (byte) 0);
        // 刷盘类型为同步刷盘时强制刷盘
        if (type == FlushDiskType.SYNC_FLUSH) {
        	// 预写的页数大于等于配置的最小预热刷盘页数时,强制刷盘
            if ((i / OS_PAGE_SIZE) - (flush / OS_PAGE_SIZE) >= pages) {
                flush = i;
                mappedByteBuffer.force();
            }
        }
        // 避免 GC
        if (j % 1000 == 0) {
            log.info("j={}, costTime={}", j, System.currentTimeMillis() - time);
            time = System.currentTimeMillis();
            try {
                Thread.sleep(0);
            } catch (InterruptedException e) {
                log.error("Interrupted", e);
            }
        }
    }
    // 预加载完成后强制刷盘
    if (type == FlushDiskType.SYNC_FLUSH) {
        log.info("mapped file warm-up done, force to disk, mappedFile={}, costTime={}",
            this.getFileName(), System.currentTimeMillis() - beginTime);
        mappedByteBuffer.force();
    }
    log.info("mapped file warm-up done. mappedFile={}, costTime={}", this.getFileName(),
        System.currentTimeMillis() - beginTime);
    this.mlock();
}

创建好 MappedFile 之后,接下来就是向 MappedFile 中追加消息:

public AppendMessageResult appendMessage(final MessageExtBrokerInner msg, final AppendMessageCallback cb) {
    return appendMessagesInner(msg, cb);
}

public AppendMessageResult appendMessagesInner(final MessageExt messageExt, final AppendMessageCallback cb) {
    assert messageExt != null;
    assert cb != null;
    // 当前写操作的位置
    int currentPos = this.wrotePosition.get();
    if (currentPos < this.fileSize) {
    	// 创建共享缓冲区
        ByteBuffer byteBuffer = writeBuffer != null ? writeBuffer.slice() : this.mappedByteBuffer.slice();
        // 设置缓冲区位置
        byteBuffer.position(currentPos);
        AppendMessageResult result = null;
        if (messageExt instanceof MessageExtBrokerInner) {
        	/* 回调追加消息 */
            result = cb.doAppend(this.getFileFromOffset(), byteBuffer, this.fileSize - currentPos, (MessageExtBrokerInner) messageExt);
        } else if (messageExt instanceof MessageExtBatch) {
            result = cb.doAppend(this.getFileFromOffset(), byteBuffer, this.fileSize - currentPos, (MessageExtBatch) messageExt);
        } else {
            return new AppendMessageResult(AppendMessageStatus.UNKNOWN_ERROR);
        }
        // 增加写操作的位置数量值
        this.wrotePosition.addAndGet(result.getWroteBytes());
        this.storeTimestamp = result.getStoreTimestamp();
        return result;
    }
    log.error("MappedFile.appendMessage return null, wrotePosition: {} fileSize: {}", currentPos, this.fileSize);
    return new AppendMessageResult(AppendMessageStatus.UNKNOWN_ERROR);
}

这里的 AppendMessageCallback 是构造 CommitLog 对象时生成的 DefaultAppendMessageCallback。
CommitLog.DefaultAppendMessageCallback:

public AppendMessageResult doAppend(final long fileFromOffset, final ByteBuffer byteBuffer, final int maxBlank,
    final MessageExtBrokerInner msgInner) {
    long wroteOffset = fileFromOffset + byteBuffer.position();
    this.resetByteBuffer(hostHolder, 8);
    String msgId = MessageDecoder.createMessageId(this.msgIdMemory, msgInner.getStoreHostBytes(hostHolder), wroteOffset);
    // 记录消费队列信息
    keyBuilder.setLength(0);
    keyBuilder.append(msgInner.getTopic());
    keyBuilder.append('-');
    keyBuilder.append(msgInner.getQueueId());
    String key = keyBuilder.toString();
    Long queueOffset = CommitLog.this.topicQueueTable.get(key);
    if (null == queueOffset) {
        queueOffset = 0L;
        CommitLog.this.topicQueueTable.put(key, queueOffset);
    }
    // 需要特殊处理的事务消息
    final int tranType = MessageSysFlag.getTransactionValue(msgInner.getSysFlag());
    switch (tranType) {
    	// Prepared 和 Rollback 消息未被消费,不会进入消费队列
        case MessageSysFlag.TRANSACTION_PREPARED_TYPE:
        case MessageSysFlag.TRANSACTION_ROLLBACK_TYPE:
            queueOffset = 0L;
            break;
        case MessageSysFlag.TRANSACTION_NOT_TYPE:
        case MessageSysFlag.TRANSACTION_COMMIT_TYPE:
        default:
            break;
    }
    // 几个序列化消息的操作
    final byte[] propertiesData =
        msgInner.getPropertiesString() == null ? null : msgInner.getPropertiesString().getBytes(MessageDecoder.CHARSET_UTF8);
    final int propertiesLength = propertiesData == null ? 0 : propertiesData.length;
    if (propertiesLength > Short.MAX_VALUE) {
        log.warn("putMessage message properties length too long. length={}", propertiesData.length);
        return new AppendMessageResult(AppendMessageStatus.PROPERTIES_SIZE_EXCEEDED);
    }
    final byte[] topicData = msgInner.getTopic().getBytes(MessageDecoder.CHARSET_UTF8);
    final int topicLength = topicData.length;
    final int bodyLength = msgInner.getBody() == null ? 0 : msgInner.getBody().length;
    final int msgLen = calMsgLength(bodyLength, topicLength, propertiesLength);
    // 判断消息体是否过大
    if (msgLen > this.maxMessageSize) {
        CommitLog.log.warn("message size exceeded, msg total size: " + msgLen + ", msg body size: " + bodyLength
            + ", maxMessageSize: " + this.maxMessageSize);
        return new AppendMessageResult(AppendMessageStatus.MESSAGE_SIZE_EXCEEDED);
    }
    // 确定是否有足够的可用空间
    if ((msgLen + END_FILE_MIN_BLANK_LENGTH) > maxBlank) {
    	// 重置 ByteBuffer
        this.resetByteBuffer(this.msgStoreItemMemory, maxBlank);
        // 总大小
        this.msgStoreItemMemory.putInt(maxBlank);
        // 文件结尾空的魔数
        this.msgStoreItemMemory.putInt(CommitLog.BLANK_MAGIC_CODE);
        // 剩余空间可以是任何值
        final long beginTimeMills = CommitLog.this.defaultMessageStore.now();
        // 写入给定的 ByteBuffer
        byteBuffer.put(this.msgStoreItemMemory.array(), 0, maxBlank);
        // 因为消息的长度加上文件末尾固定留的长度大于文件最大的剩余空间,所以这里的空间已经不够了,也就是已经到了文件的结尾
        // 返回 AppendMessageStatus.END_OF_FILE 状态后续会创建新的文件继续写入
        return new AppendMessageResult(AppendMessageStatus.END_OF_FILE, wroteOffset, maxBlank, msgId, msgInner.getStoreTimestamp(),
            queueOffset, CommitLog.this.defaultMessageStore.now() - beginTimeMills);
    }
    // 初始化存储空间
    this.resetByteBuffer(msgStoreItemMemory, msgLen);
    // 4字节的总大小
    this.msgStoreItemMemory.putInt(msgLen);
    // 4字节的文件结尾空的魔数
    this.msgStoreItemMemory.putInt(CommitLog.MESSAGE_MAGIC_CODE);
    // 4字节的消息体CRC校验和
    this.msgStoreItemMemory.putInt(msgInner.getBodyCRC());
    // 4字节的队列 id
    this.msgStoreItemMemory.putInt(msgInner.getQueueId());
    // 4字节的 flag
    this.msgStoreItemMemory.putInt(msgInner.getFlag());
    // 8字节的队列偏移量
    this.msgStoreItemMemory.putLong(queueOffset);
    // 8字节的物理偏移量
    this.msgStoreItemMemory.putLong(fileFromOffset + byteBuffer.position());
    // 4子节的系统标识
    this.msgStoreItemMemory.putInt(msgInner.getSysFlag());
    // 8字节的消息出生时间戳
    this.msgStoreItemMemory.putLong(msgInner.getBornTimestamp());
    // 消息出生 host 主机
    this.resetByteBuffer(hostHolder, 8);
    this.msgStoreItemMemory.put(msgInner.getBornHostBytes(hostHolder));
    // 8字节的存储时间戳
    this.msgStoreItemMemory.putLong(msgInner.getStoreTimestamp());
    // 消息存储 host 主机
    this.resetByteBuffer(hostHolder, 8);
    this.msgStoreItemMemory.put(msgInner.getStoreHostBytes(hostHolder));
    // 4字节的重试次数
    this.msgStoreItemMemory.putInt(msgInner.getReconsumeTimes());
    // 8字节的事务准备偏移量
    this.msgStoreItemMemory.putLong(msgInner.getPreparedTransactionOffset());
    // 4字节的消息体长度
    this.msgStoreItemMemory.putInt(bodyLength);
    if (bodyLength > 0)
    	// 消息体内容
        this.msgStoreItemMemory.put(msgInner.getBody());
    // topic 长度
    this.msgStoreItemMemory.put((byte) topicLength);
    // topic 内容
    this.msgStoreItemMemory.put(topicData);
    // properties 长度
    this.msgStoreItemMemory.putShort((short) propertiesLength);
    if (propertiesLength > 0)
    	// properties 内容
        this.msgStoreItemMemory.put(propertiesData);
    final long beginTimeMills = CommitLog.this.defaultMessageStore.now();
    // 将消息写入队列缓冲区
    byteBuffer.put(this.msgStoreItemMemory.array(), 0, msgLen);
    AppendMessageResult result = new AppendMessageResult(AppendMessageStatus.PUT_OK, wroteOffset, msgLen, msgId,
        msgInner.getStoreTimestamp(), queueOffset, CommitLog.this.defaultMessageStore.now() - beginTimeMills);
    switch (tranType) {
        case MessageSysFlag.TRANSACTION_PREPARED_TYPE:
        case MessageSysFlag.TRANSACTION_ROLLBACK_TYPE:
            break;
        case MessageSysFlag.TRANSACTION_NOT_TYPE:
        case MessageSysFlag.TRANSACTION_COMMIT_TYPE:
        	// 下次更新 ConsumeQueue 信息
            CommitLog.this.topicQueueTable.put(key, ++queueOffset);
            break;
        default:
            break;
    }
    return result;
}
RocketMQ Broker消息处理流程及部分源码解析 📆 最近更新:2023年2月10日🍊 个人简介:通信工程本硕 for NJU💪、Java程序员🌕。做过科研paper,发过专利,优秀的程序员不应该只是CRUD。 阅读详情

相关推荐

RocketMQ源码解析:Producer发送消息+Broker消息存储

文章目录1. Producer 发送消息2. Broker 接收消息 1. Producer 发送消息 先上一段简单的生产者代码 public static void main(String[] args) throws Exception { DefaultMQProducer producer = new DefaultMQProducer("default_producer"); producer.setNamesrvAddr("127.0.0.1:9876")

qq_28834355的博客 302

Broker存储机制详解

文章目录Broker详解Broker概述Broker启动和停止流程Broker存储机制为什么写文件这么快Broker存储消息流程详解(1)Broker接收客户端发送消息的请求并做预处理(2)Broker存储前消息预处理(3)消息校验和存储模块校验(4)将消息写入CommitLogBroker读写分离机制Master-Slave读写分离Direct Memory-Page Cache读写分离 Broker详解 Broker概述 Broker是RocketMQ体系中的核心组件之一,存储是Broker的核心功能之

weixin_43248318的博客 2020

正交试验-方差分析-数据展现形式

方差分析(ANOVA, Analysis of Variance)用于比较多个组之间的均值差异,确定因素对响应变量的显著性影响。示例分析。

m0_58326994的博客 1976

【kafka参数配置--broker】

############################# System ############################# #唯一标识在集群中的ID,要求是正数。 broker.id=0 #服务端口,默认9092 port=9092 #监听地址,不设为所有地址 host.name=debugo01   # 处理网络请求的最大线程数 num.network.threa...

319

ASReview:基于主动学习的AI文献筛选工具,提升科研效率

主动学习是机器学习的一个重要分支,其核心原理是让算法能够主动选择最有价值的数据进行标注,从而以更低的成本获得更好的模型性能。这一技术通过人机协作的闭环流程,显著提升了数据标注和模型训练的效率和精度。在工程实践中,主动学习尤其适用于数据标注成本高昂或数据类别不平衡的场景,例如医学影像分析、自然语言处理中的文本分类以及推荐系统的冷启动问题。通过优先标注模型最不确定的样本,它能够有效解决传统机器学习面临的冷启动和数据稀疏性挑战。本文聚焦的ASReview项目,正是将主动学习原理应用于系统文献综述这一具体场景,通过

weixin_28725959的博客 442

双目视觉入门实战:用Matlab标定相机,再到Python OpenCV完成测距的完整链路

本文详细介绍了双目视觉技术的完整实现流程,从Matlab相机标定到Python OpenCV测距的全链路实践。重点解析了Matlab与OpenCV的参数转换技巧,以及立体校正、视差计算等关键步骤的代码实现,帮助开发者快速掌握双目测距系统的搭建方法。

weixin_29166013的博客 455

详解RocketMQ消息存储机制

值得关注的是, IndexFile 条目中存储的不是消息索引key 而是消息属性key 的HashCode ,在根据key 查找时需要根据消息物理偏移量找到消息进而再验证消息key 的值,之所以只存储Hash Code 而不存储具体的key , 是为了将Index 条目设计为定长结构,才能方便地检索与定位条目。Step5 : 更新文件索引头信息。

白话机器学习 1539

故障诊断 | 小波变换机械设备外圈振动信号故障诊断

故障诊断 | 小波变换机械设备外圈振动信号故障诊断

天天酷科研的博客 510

RocketMQ ConsumeQueue 消费队列文件

1. 概述 1.1 ConsumeQueue 是什么 ConsumeQueue,又称作消费队列,是 RocketMQ 存储系统的一部分,保存在磁盘中。 该文件可以看作 CommitLog 关于消息消费的“索引”文件。 ConsumeQueue 是一个 MappedFileQueue,即每个文件大小相同的内存映射文件队列。每个文件由大小和格式相同的索引项构成。 每一个 Topic 的 Queue,都对应一个 ConsumeQueue。 1.2 ConsumeQueue 的作用 引入 ConsumeQueue

金甲虫的博客 3180

YOLOv5改进 | 多尺度特征提取 | 结合多样分支块及融合的高级设计(CVPR2021)

YOLOv5改进 | 多尺度特征提取 | 结合多样分支块及融合的高级设计(CVPR2021)

qq_44224801的博客 2070

【WorkBuddy专栏】完结篇暨付费专栏总目录(内容继续更新中)

【WorkBuddy专栏】完结篇和付费内容总目录

AI人人懂 952

Kafka学习之broker配置(0.8.1版)

broker.id  默认值:无 每一个broker都有一个唯一的id,这是一个非负整数,这个id就是broker的"名字",这样就允许broker迁移到别的机器而不会影响消费者。你可以选择任意一个数字,只要它是唯一的。   log.dirs 默认值:/tmp/kafka-logs 一个用逗号分隔的目录列表,可以有多个,用来为Kafka存储数据。每当需要为一个新的partition分配...

xcc的博客 434

rosbag分析传感器数据的时间同步情况方法

ROS传感器时间同步分析流程:通过rosbaginfo初步检查bag文件信息,使用rqt_bag可视化时间线分布,采用rostopicecho或Python脚本提取各传感器时间戳并计算时间差统计值(均值/最大差/标准差),最后分析接收与采样时间延迟。量化评估同步精度,识别固定偏移或随机抖动问题,确保多传感器数据对齐,为后续融合处理提供可靠数据基础。

start_up_go的博客 206

RocketMQ源码解析之Broker消息存储(消息存储)

接上篇RocketMQ源码解析之Broker消息存储(消息接收) DefaultMessageStore#asyncPutMessage /** * 进行存储 * * @param msg MessageInstance to store * @return */ @Override public CompletableFuture<PutMessageResult> as...

fengwuya的博客 341

Coze 打通飞书多维表格,实现数据增删改查操作实战详解

基于Coze 打通飞书多维表实现数据录入系统实战详解

congge 5792

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

RocketMQ源码解析之broker消息存储流程(PutMessage)

原创不易,转载请注明出处 文章目录前言1. 消息存储流程2. commitLog写入消息源码解析总结 前言 本文主要是解析下broker 的消息存储部分,看下broker是怎样存储消息的,比如说我消息生产者发送过来一个消息,然后broker 是怎样存储的,需要注意的是在RocketMQ集群架构中只有master角色的broker是可以接收消息生产者消息的,slave角色的broker只能是master同步给它,但是消息消费者是有机会从slave角色上面拉取消息的,这个是要看slave同步情况与mast.

猿上生活 2097

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

RocketMQ源码解析之broker消息存储流程(BuildIndex)

文章目录 ### 前言 ### 1.BuildIndex ### 2. BuildIndex源码解析 ### 总结

猿上生活 966

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

RocketMQ源码解析之broker消息存储流程(Reput ConsumeQueue)

原创不易,转载请注明出处 文章目录前言1. reput到consumeQueue工作流程介绍1.1 消息写入commitlog流程回顾1.2 consumeQueue流程介绍2.reput到consumeQueue源码解析总结 前言 我们在《RocktMQ源码解析之broker消息存储流程(最最最硬核一)》一文中介绍解析了broker接收到消息,然后写入到commitlog中,将写入结果返回给消息生产者这么一个过程,这个其实就是普通消息send到broker的一个过程了,到这,消息生产者就可以任务它这.

猿上生活 1336

RocketMQ源码解析-Broker的消息存储

Broker接收得到的来自provider的消息在sendMessageProcessor的sendMessage()方法当中处理。 在sendMessage()方法当中会直接将所接收得到的消息封装为MessageExtBrokerInner。 MessageExtBrokerInner msgInner = new MessageExtBrokerInner(); msgInner.set...

不说话装高手 1256

RocketMQ源码解析四(Broker接收以及存储消息)

接收请求的入口已经在上篇分析过了,所以这里直接看处理器如何处理请求。

指尖凉的博客 461

RocketMQ源码解析之Broker消息存储(刷盘机制)

  在上篇RocketMQ源码解析之Broker消息存储(消息存储)中分析了消息如何从Broker存储到MappedFile内存缓冲区,但还没有存储到文件中,即还没有刷盘,本篇将介绍RocketMQ如何进行刷盘的   RocketMQ 的读写时基于NIO的内存映射机制的,进行消息存储时先将消息追加到MappedFile,然后根据不同的刷盘策略进行刷盘。同步刷盘是先将消息追加到内存后,将同步调用M...

fengwuya的博客 324

RocketMQ 从哪入手

RocketMQ 从哪入手1.MQ的优缺点?当前常用MQ的对比?MQ的优缺点当前常用MQ的对比2.自己的学习方法(菜鸡)3.自己部署的步骤、遇到的一些问题,以及解决方案4.集群的搭建方式(以双主双从为例子)5.RocketMQ中NameServer相关部分源码解析 1.MQ的优缺点?当前常用MQ的对比? MQ的优缺点 优点: 解耦 削峰 分发(数据) 缺点: 系统可用性降低 系统复杂度提高(重复消费,消息丢失,顺序消费) 一致性问题 当前常用MQ的对比 现在主流MQ主要有三种 : Rock

dzr123123的博客 245

RocketMQ核心源码解读

《RocketMQ核心源码解析》摘要:本文深入剖析了Apache RocketMQ 5.x的核心架构与实现机制。从源码环境搭建入手,详细解析了NameServer轻量级路由管理、Broker启动流程及网络通信框架设计。重点分析了消息生产/消费流程、存储引擎优化(CommitLog顺序写+ConsumeQueue索引)、延迟消息时间轮算法和零拷贝技术(mmap+sendfile)等高并发设计精髓。通过文件预热、内存池化、线程隔离等关键技术,RocketMQ实现了高性能消息处理。文中还提供了源码阅读方法论和实验

weixin_74024217的博客 969

RocketMQ源码学习

RocketMQ源码学习 文章目录RocketMQ源码学习Producer 是怎么将消息发送至 Broker 的?同步发送异步发送队列选择器事务消息原理Broker 是怎么处理客户端发送的消息?NettyRequestProcessor发送消息事务消息客户端怎么获取 Broker 信息?客户端怎么获取队列信息? Producer 是怎么将消息发送至 Broker 的? 同步发送 RocketMQ ...

Switch的博客 1128

03 RocketMQ - Broker 源码分析

03 RocketMQ - Broker 源码分析

刘元雄 990

第十九章-消息重推-Broker端处理

消息重推-Broker端处理

zhang527294844的博客 864
上一篇: RocketMQ源码解析—Broker处理消息发送请求
下一篇: RocketMQ源码解析之Broker消息刷盘
0xZzzz
博客等级 码龄16年 280粉丝 100原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值