RocketMQ 发送消息存储流程

存储总览

业务系统大多数需要 MQ 有持久存储的能力,能大大增加系统的高可用性。从存储方式和效率来看,文件系统高于 KV 存储,KV 存储又高于关系型数据库,直接操作文件系统肯定是最快的,但可靠性却是最低的,而关系型数据库的性能和可靠性与文件系统恰恰相反。

存储实现

  • RocketMQ 存储概要设计
  • 消息发送存储流程
  • 存储文件组织与内存映射机制
  • RocketMQ 存储文件
  • 消息队列、索引文件构建和机制
  • RocketMQ 文件恢复机制
  • RocketMQ 刷盘机制
  • RocketMQ 文件删除机制

存储概要设计

RocketMQ 主要存储的文件包括 Commitlog 文件、ConsumeQueue 文件、IndexFile 文件。

RocketMQ 将所有主题的消息存储在同一个文件中,确保消息发送时顺写文件,尽最大的能力确保消息发送的高性能与高吞吐量。但由于消息中间件一般是基于消息主题的订阅机制,这样便给按照消息主题检索消息带来了极大的不便。为了提高消息消费的效率,RocketMQ 引入了 ConsumeQueue 消息队列文件,每个消息主题包含多个消息消费队列,每一个消息队列有一个消息文件。Consumer消费是已 Topic 为粒度的,但是CommitLog是所有Topic消息的汇总存储,这时候需要一个已Topic为维度的commitLog文件offset的索引,便于消费这个Topic 下的数据,因此产生了 ConsumeQueue。相当于一个Topic下,有多个MessageQueue消息队列,然后将消息队列映射为ConsumeQueue消息消费队列,供consumer 快捷消费这个Topic下的数据。

IndexFile 索引文件,其主要设计理念就是为了加速消息的检索性能,根据消息的属性快速从 CommitLog 文件中检索消息。RocketMQ 是一款高性能的消息中间件,存储部分的设计是核心,存储的核心是IO的访问性能,IO访问性能是怎样提高的呢?我们先看一下 RocketMQ 消息存储数据流向:如图:
image.png

  • CommitLog:消息存储文件,所有消息主题的消息都存储在 CommitLog文件中
  • ConsumeQueue:消息消费队列,消息到达 CommitLog 文件后,将异步转发到消息消费队列,是一个CommitLog文件以Topic为主体的,供消息消费。
  • IndexFile:消息索引文件,主要存储消息 Key 与 Offset 的对应关系。
  • 事务状态服务:存储每条消息的事务状态。
  • 定时消息服务:每一个延迟级别对应一个消息消费队列,存储延迟队列的消息拉取进度。

发送消息存储流程

Broker接受消息处理器

依据Netty处理Qequest请求的模式,只需要注册好相应的Processor,就可以处理Producer发送消息的请求。在BrokerController中新建SendMessageProcessor对象,用来接受发送的消息请求,然后创建sendMessageExecutor对象,是一个处理发送消息的具体执行器。然后还BrokerController创建DefaultMessageStore对象,消息存储服务的主要实现类。

#org.apache.rocketmq.broker.BrokerController

// 消息处理器
SendMessageProcessor sendProcessor = new SendMessageProcessor(this);

// broker 处理 producer 发送消息请求的执行器
this.sendMessageExecutor = new BrokerFixedThreadPoolExecutor(
    this.brokerConfig.getSendMessageThreadPoolNums(),
    this.brokerConfig.getSendMessageThreadPoolNums(),
    1000 * 60,
    TimeUnit.MILLISECONDS,
    this.sendThreadPoolQueue,
    new ThreadFactoryImpl("SendMessageThread_"));	

// 注册处理消息请求处理器
this.remotingServer.registerProcessor(RequestCode.SEND_MESSAGE, sendProcessor, this.sendMessageExecutor);

// 消息存储服务
this.messageStore =
    new DefaultMessageStore(this.messageStoreConfig, this.brokerStatsManager, this.messageArrivingListener,
        this.brokerConfig);	

DefaultMessageStore存储文件操作API

DefaultMessageStore主要成员属性介绍,主要是为消息存储、mappedFile文件操作、写入磁盘等服务。

// 消息存储配置属性
private final MessageStoreConfig messageStoreConfig;
// CommitLog
// 文件存储实现类
private final CommitLog commitLog;
// 消息队列存储缓存表,按消息主题分组
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;
// 存储 HA 机制
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;
// broker 配置属性
private final BrokerConfig brokerConfig;

private volatile boolean shutdown = true;
// 文件刷盘检测点
private StoreCheckpoint storeCheckpoint;

private AtomicLong printTimes = new AtomicLong(0);
// CommitLog 文件转发请求
private final LinkedList<CommitLogDispatcher> dispatcherList;
// 一个可以读写的 lock 文件
private RandomAccessFile lockFile;
Broker接受消息存储流程

image.png

这里先介绍消息在Broker的存储流程,看懂这个流程就好,其中涉及到的CommitLog作用、mappedFile文件操作等等,将在以后详细介绍。

  1. org.apache.rocketmq.store.DefaultMessageStore#putMessage()

DefaultMessageStore#putMessage() 存储消息,Broker状态和消息合理性的检测,调用CommitLog#putMessage()方法。

  1. org.apache.rocketmq.store.CommitLog#putMessage()

Commitlog 存放消息,存放消息到系统内存映射中,并没有落入磁盘中,等待同步刷盘、或者异步刷盘,然后是消息存储的高可用。

  1. org.apache.rocketmq.store.MappedFile#appendMessage()

appendMessage的重载方法

  1. org.apache.rocketmq.store.MappedFile.appendMessagesInner()

获取MappedFile中的MappedByteBuffer或者WriteBuffer进行message的存储,两者都是直接内存,MappedFile知识会在下一节详细介绍,这里有一个存储流程的印象就好。

  1. org.apache.rocketmq.store.CommitLog#doAppend()

将消息存储到ByteBuffer直接内存中,然后返回存储成功的结果。存储到ByteBuffer并不是终点,然后还有ByteBuffer中的数据刷新到磁盘中,这个将在下面一节详细介绍ByteBuffer中的数据操作。

Step1

DefaultMessageStore#putMessage() 存储消息,Broker状态和消息合理性的检测,调用CommitLog#putMessage()方法。

/**
 * 消息存储到broker磁盘文件中
 * @param msg Message instance to store
 * @return
 */
@Override
public PutMessageResult putMessage(MessageExtBrokerInner msg) {
    // 检测broker 状态
    PutMessageStatus checkStoreStatus = this.checkStoreStatus();
    if (checkStoreStatus != PutMessageStatus.PUT_OK) {
        return new PutMessageResult(checkStoreStatus, null);
    }
    // 检测消息是否合格
    PutMessageStatus msgCheckStatus = this.checkMessage(msg);
    if (msgCheckStatus == PutMessageStatus.MESSAGE_ILLEGAL) {
        return new PutMessageResult(msgCheckStatus, null);
    }
    // 获取系统时间
    long beginTime = this.getSystemClock().now();
    // 存储消息
    PutMessageResult result = this.commitLog.putMessage(msg);
    // 花费时间
    long elapsedTime = this.getSystemClock().now() - beginTime;
    if (elapsedTime > 500) {
        log.warn("not in lock elapsed time(ms)={}, bodyLength={}", elapsedTime, msg.getBody().length);
    }
    // 设置存放消息的最大时间
    this.storeStatsService.setPutMessageEntireTimeMax(elapsedTime);
    // 存放失败,更新次数
    if (null == result || !result.isOk()) {
        this.storeStatsService.getPutMessageFailedTimes().incrementAndGet();
    }

    return result;
}
Step2

Commitlog 存放消息,存放消息到系统内存映射中,并没有落入磁盘中,等待同步刷盘、或者异步刷盘,然后是消息存储的高可用。

/**
 * commitlog 存放消息,存放消息到系统内存映射中,并没有落入磁盘中,等待同步刷盘、或者异步刷盘,然后是消息存储的高可用。
 */
public PutMessageResult putMessage(final MessageExtBrokerInner msg) {
    // Set the storage time
    // 消息存储时间
    msg.setStoreTimestamp(System.currentTimeMillis());
    // Set the message body BODY CRC (consider the most appropriate setting
    // on the client)
    // 循环冗余校验码,检测数据在网络中传输是否发生变化
    msg.setBodyCRC(UtilAll.crc32(msg.getBody()));
    // Back to Results
    AppendMessageResult result = null;

    StoreStatsService storeStatsService = this.defaultMessageStore.getStoreStatsService();
    // topic
    String topic = msg.getTopic();
    int queueId = msg.getQueueId();
    // 事务回滚消息标志
    final int tranType = MessageSysFlag.getTransactionValue(msg.getSysFlag());
    // 如果是非事务消息,或者事务消息的 commit 操作;进而判断是不是延迟消息,存储到特殊的延迟消息队列;然后事务消息存储也进行了同样的消息 topic 的转换,从而实现了消息的事务;事务消息非提交阶段,先进行另一个 topic 的储存,如果事务提交了,才进行,存储到消息的真正的topic 中去。
    if (tranType == MessageSysFlag.TRANSACTION_NOT_TYPE
        || tranType == MessageSysFlag.TRANSACTION_COMMIT_TYPE) {
        // Delay Delivery
        // 如果是延迟级别消息
        if (msg.getDelayTimeLevel() > 0) {
            // 设置消息延迟级别
            if (msg.getDelayTimeLevel() > this.defaultMessageStore.getScheduleMessageService().getMaxDelayLevel()) {
                msg.setDelayTimeLevel(this.defaultMessageStore.getScheduleMessageService().getMaxDelayLevel());
            }
            // 延迟消息topic
            topic = TopicValidator.RMQ_SYS_SCHEDULE_TOPIC;
            // 延迟消息消息队列Id
            queueId = ScheduleMessageService.delayLevel2QueueId(msg.getDelayTimeLevel());

            // Backup real topic, queueId
            // 将真实的 topic 放入 message 属性中
            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()));
            // 替换为延迟消息topic
            msg.setTopic(topic);
            msg.setQueueId(queueId);
        }
    }
    // 消息诞生地址 ipv6 设置
    InetSocketAddress bornSocketAddress = (InetSocketAddress) msg.getBornHost();
    if (bornSocketAddress.getAddress() instanceof Inet6Address) {
        msg.setBornHostV6Flag();
    }
    // 消息存储地址 ipv6 设置
    InetSocketAddress storeSocketAddress = (InetSocketAddress) msg.getStoreHost();
    if (storeSocketAddress.getAddress() instanceof Inet6Address) {
        msg.setStoreHostAddressV6Flag();
    }

    long elapsedTimeInLock = 0;

    MappedFile unlockMappedFile = null;
    // 最后一个 消息 存储 commitlog 消息映射文件
    MappedFile mappedFile = this.mappedFileQueue.getLastMappedFile();
    // 自旋锁 或 可重入锁,上锁;消息写入 commitlog 的映射文件是串行的
    putMessageLock.lock(); //spin or ReentrantLock ,depending on store config
    try {
        // 开始上锁时间
        long beginLockTimestamp = this.defaultMessageStore.getSystemClock().now();
        this.beginTimeInLock = beginLockTimestamp;

        // Here settings are stored timestamp, in order to ensure an orderly
        // global
        // 消息存储时间,确定消息全局有序
        msg.setStoreTimestamp(beginLockTimestamp);
        // mappedFile 存储满或者 isnull,
        if (null == mappedFile || mappedFile.isFull()) {
            mappedFile = this.mappedFileQueue.getLastMappedFile(0); // Mark: NewFile may be cause noise;新文件,造成脏数据
        }
        // 创建 mappedFile 失败
        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);
        }
        // 追加消息到 mappedFile 文件中
        result = mappedFile.appendMessage(msg, this.appendMessageCallback);
        switch (result.getStatus()) {
            case PUT_OK:
                break;
            case END_OF_FILE:
                // broker 重新开辟,新的 commitlog 文件
                unlockMappedFile = mappedFile;
                // Create a new file, re-write the message
                mappedFile = this.mappedFileQueue.getLastMappedFile(0);
                if (null == mappedFile) {
                    // XXX: warn and notify me
                    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);
        }
        // 存储消息花费时间
        elapsedTimeInLock = this.defaultMessageStore.getSystemClock().now() - beginLockTimestamp;
        beginTimeInLock = 0;
    } finally {
        // 最后释放存储消息的锁
        putMessageLock.unlock();
    }
    // 存储消息花费时间 > 500
    if (elapsedTimeInLock > 500) {
        log.warn("[NOTIFYME]putMessage in lock cost time(ms)={}, bodyLength={} AppendMessageResult={}", elapsedTimeInLock, msg.getBody().length, result);
    }

    if (null != unlockMappedFile && this.defaultMessageStore.getMessageStoreConfig().isWarmMapedFileEnable()) {
        this.defaultMessageStore.unlockMappedFile(unlockMappedFile);
    }

    PutMessageResult putMessageResult = new PutMessageResult(PutMessageStatus.PUT_OK, result);

    // Statistics
    // topic 下存放消息次数
    storeStatsService.getSinglePutMessageTopicTimesTotal(msg.getTopic()).incrementAndGet();
    // topic 下存放消息字节数
    storeStatsService.getSinglePutMessageTopicSizeTotal(topic).addAndGet(result.getWroteBytes());
    // handle 硬盘刷新
    handleDiskFlush(result, putMessageResult, msg);
    // handle 高可用
    handleHA(result, putMessageResult, msg);
    // 返回存储消息的结果
    return putMessageResult;
}
Step3

appendMessage的重载方法

// 追加消息到 mappedFile 文件中
public AppendMessageResult appendMessage(final MessageExtBrokerInner msg, final AppendMessageCallback cb) {
    return appendMessagesInner(msg, cb);
}
Step4

获取MappedFile中的MappedByteBuffer或者WriteBuffer进行message的存储,两者都是直接内存,MappedFile知识会在下一节详细介绍,这里有一个存储流程的印象就好。

// 追加消息到 mappedFile 文件中
public AppendMessageResult appendMessagesInner(final MessageExt messageExt, final AppendMessageCallback cb) {
    assert messageExt != null;
    assert cb != null;
    // 当前消息写入的位置
    int currentPos = this.wrotePosition.get();
    // 如果位置超过文件大小,抛出 UNKNOWN_ERROR 未知错误异常;
    // 小于文件大小,进行消息存储
    if (currentPos < this.fileSize) {
        // slice 薄片,创建一个与 MappedFile 的共享内存区,并设置 position 当前指针。
        ByteBuffer byteBuffer = writeBuffer != null ? writeBuffer.slice() : this.mappedByteBuffer.slice();
        byteBuffer.position(currentPos);
        AppendMessageResult result;
        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);
}
Step5

将消息存储到ByteBuffer直接内存中,然后返回存储成功的结果。存储到ByteBuffer并不是终点,然后还有ByteBuffer中的数据刷新到磁盘中,这个将在下面一节详细介绍ByteBuffer中的数据操作。

// 追加消息到mappedFile的内存映射文件
public AppendMessageResult doAppend(final long fileFromOffset, final ByteBuffer byteBuffer, final int maxBlank,
    final MessageExtBrokerInner msgInner) {
    // STORETIMESTAMP + STOREHOSTADDRESS + OFFSET <br>

    // PHY OFFSET
    // 消息存储结束的offset
    long wroteOffset = fileFromOffset + byteBuffer.position();

    int sysflag = msgInner.getSysFlag();
    // 消息出生地ip地址长度
    int bornHostLength = (sysflag & MessageSysFlag.BORNHOST_V6_FLAG) == 0 ? 4 + 4 : 16 + 4;
    // 消息存储地ip地址的长度
    int storeHostLength = (sysflag & MessageSysFlag.STOREHOSTADDRESS_V6_FLAG) == 0 ? 4 + 4 : 16 + 4;
    // 分配地址
    ByteBuffer bornHostHolder = ByteBuffer.allocate(bornHostLength);
    ByteBuffer storeHostHolder = ByteBuffer.allocate(storeHostLength);

    this.resetByteBuffer(storeHostHolder, storeHostLength);
    // 创建消息Id: 4字节IP+4字节端口号+8字节消息偏移量
    String msgId;
    if ((sysflag & MessageSysFlag.STOREHOSTADDRESS_V6_FLAG) == 0) {
        msgId = MessageDecoder.createMessageId(this.msgIdMemory, msgInner.getStoreHostBytes(storeHostHolder), wroteOffset);
    } else {
        msgId = MessageDecoder.createMessageId(this.msgIdV6Memory, msgInner.getStoreHostBytes(storeHostHolder), wroteOffset);
    }

    // Record ConsumeQueue information
    // 获取该消息在消息队列的偏移量,方便存储在消费消息队列中,从而方便消息查找
    keyBuilder.setLength(0);
    keyBuilder.append(msgInner.getTopic());
    keyBuilder.append('-');
    keyBuilder.append(msgInner.getQueueId());
    // 消息的key
    String key = keyBuilder.toString();
    // 消息的commitlog偏移量,然后存储在 consumequeue 中,方便消息查找
    Long queueOffset = CommitLog.this.topicQueueTable.get(key);
    // 空,就是就是
    if (null == queueOffset) {
        queueOffset = 0L;
        // key,和 offset 的,根据消息 key 进行查询时 ,方便消息查询,相当于 key 的索引
        CommitLog.this.topicQueueTable.put(key, queueOffset);
    }
    // 事务消息特殊处理
    // Transaction messages that require special handling
    final int tranType = MessageSysFlag.getTransactionValue(msgInner.getSysFlag());
    switch (tranType) {
        // 预提交和rollback 消息是不会被消费的,不会进入 consume queue 中
        // Prepared and Rollback message is not consumed, will not enter the
        // consume queue
        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;
    }
    // 消息属性信息序列化
    /**
     * Serialize message
     */
    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);
    }
    // topic 字节数组
    final byte[] topicData = msgInner.getTopic().getBytes(MessageDecoder.CHARSET_UTF8);
    // topic 长度
    final int topicLength = topicData.length;
    // 消息体长度
    final int bodyLength = msgInner.getBody() == null ? 0 : msgInner.getBody().length;
    // 计算消息长度
    final int msgLen = calMsgLength(msgInner.getSysFlag(), bodyLength, topicLength, propertiesLength);

    // Exceeds the maximum message
    // 超过最大消息长度,报错
    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);
    }

    // Determines whether there is sufficient free space
    // maxBlank:消息空闲长度
    // 消息长度+文件结束8个空的字节长度;大于消息空闲长度;返回文件结束的标志
    if ((msgLen + END_FILE_MIN_BLANK_LENGTH) > maxBlank) {
        this.resetByteBuffer(this.msgStoreItemMemory, maxBlank);
        // 1 TOTALSIZE
        this.msgStoreItemMemory.putInt(maxBlank);
        // 2 MAGICCODE
        this.msgStoreItemMemory.putInt(CommitLog.BLANK_MAGIC_CODE);
        // 3 The remaining space may be any value
        // Here the length of the specially set maxBlank
        final long beginTimeMills = CommitLog.this.defaultMessageStore.now();
        byteBuffer.put(this.msgStoreItemMemory.array(), 0, maxBlank);
        // 返回文件空闲长度不够,END_OF_FILE;Broker 会重新创建一个新的 CommitLog 文件来存储该消息。
        return new AppendMessageResult(AppendMessageStatus.END_OF_FILE, wroteOffset, maxBlank, msgId, msgInner.getStoreTimestamp(),
            queueOffset, CommitLog.this.defaultMessageStore.now() - beginTimeMills);
    }

    // Initialization of storage space
    // 初始化存储空间的内容
    // 重置 bytebuffer 缓存,存储内容,存储大小
    this.resetByteBuffer(msgStoreItemMemory, msgLen);
    // 1 TOTALSIZE
    this.msgStoreItemMemory.putInt(msgLen);
    // 2 MAGICCODE
    this.msgStoreItemMemory.putInt(CommitLog.MESSAGE_MAGIC_CODE);
    // 3 BODYCRC
    this.msgStoreItemMemory.putInt(msgInner.getBodyCRC());
    // 4 QUEUEID
    this.msgStoreItemMemory.putInt(msgInner.getQueueId());
    // 5 FLAG
    this.msgStoreItemMemory.putInt(msgInner.getFlag());
    // 6 QUEUEOFFSET
    this.msgStoreItemMemory.putLong(queueOffset);
    // 7 PHYSICALOFFSET
    this.msgStoreItemMemory.putLong(fileFromOffset + byteBuffer.position());
    // 8 SYSFLAG
    this.msgStoreItemMemory.putInt(msgInner.getSysFlag());
    // 9 BORNTIMESTAMP
    this.msgStoreItemMemory.putLong(msgInner.getBornTimestamp());
    // 10 BORNHOST
    this.resetByteBuffer(bornHostHolder, bornHostLength);
    this.msgStoreItemMemory.put(msgInner.getBornHostBytes(bornHostHolder));
    // 11 STORETIMESTAMP
    this.msgStoreItemMemory.putLong(msgInner.getStoreTimestamp());
    // 12 STOREHOSTADDRESS
    this.resetByteBuffer(storeHostHolder, storeHostLength);
    this.msgStoreItemMemory.put(msgInner.getStoreHostBytes(storeHostHolder));
    // 13 RECONSUMETIMES
    this.msgStoreItemMemory.putInt(msgInner.getReconsumeTimes());
    // 14 Prepared Transaction Offset
    this.msgStoreItemMemory.putLong(msgInner.getPreparedTransactionOffset());
    // 15 BODY
    this.msgStoreItemMemory.putInt(bodyLength);
    if (bodyLength > 0)
        this.msgStoreItemMemory.put(msgInner.getBody());
    // 16 TOPIC
    this.msgStoreItemMemory.put((byte) topicLength);
    this.msgStoreItemMemory.put(topicData);
    // 17 PROPERTIES
    this.msgStoreItemMemory.putShort((short) propertiesLength);
    if (propertiesLength > 0)
        this.msgStoreItemMemory.put(propertiesData);
    // 开始存储写入mappedFile 的时间
    final long beginTimeMills = CommitLog.this.defaultMessageStore.now();
    // Write messages to the queue buffer
    // 写消息内容到 byteBuffer
    byteBuffer.put(this.msgStoreItemMemory.array(), 0, msgLen);
    //返回消息存储 mappedFile 映射的buffer 成功
    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:
            // The next update ConsumeQueue information
            CommitLog.this.topicQueueTable.put(key, ++queueOffset);
            break;
        default:
            break;
    }
    return result;
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值