CommitLog——MQ的消息的存储


在消息队列(Message Queue, MQ)系统中, CommitLog是消息存储的一种重要机制,它确保消息能够被持久化并且在系统出现故障时能够被正确地恢复。下面我们将详细介绍MQ中的 CommitLog机制以及消息是如何存储的。

MQ中的消息存储

1. 概述

在大多数消息队列系统中,消息首先被写入到CommitLog中,这是一个顺序写入的日志文件。这样做的好处是顺序写入磁盘的效率非常高,因为现代硬盘和SSD对于顺序写入的支持非常好。

2. CommitLog的特点
  • 顺序写入:消息按顺序写入到CommitLog文件中,这有助于提高写入速度。
  • 持久化CommitLog文件通常是磁盘上的文件,因此能够保证消息的持久化。
  • 故障恢复:如果系统发生崩溃,可以通过重放CommitLog文件来恢复消息状态。
  • 写前日志:在消息被真正处理之前,其变更就被写入CommitLog中,确保了数据的安全性。
3. 存储过程
  1. 消息接收:当客户端向MQ发送消息时,这些消息首先被写入到CommitLog中。
  2. 消息确认:一旦消息被写入CommitLog,MQ就会向客户端返回确认消息已被成功接收。
  3. 消息持久化:为了确保数据的安全性,CommitLog中的数据需要被刷新到磁盘上。这可以通过同步或异步的方式完成。
  4. 消息索引:为了快速定位消息,MQ还需要维护一个消息索引。这个索引通常会记录每条消息在CommitLog中的位置,以便消费者可以快速查找并消费消息。
4. 具体实现

以Apache RocketMQ为例,RocketMQ中的CommitLog机制如下:

  • 消息写入:当消息被发送到Broker时,Broker会首先将消息写入到CommitLog文件中。
  • 数据刷新:Broker可以选择同步或异步地将数据刷新到磁盘上。
  • 消息索引:RocketMQ还维护了一个消息索引文件,记录每条消息在CommitLog中的起始位置,以加速消息的查找。
  • 文件管理CommitLog文件通常按照一定的大小分割成多个文件,以方便管理和减少单个文件的大小。
5. 故障恢复
  • 重放CommitLog:在系统重启时,Broker会重放CommitLog文件,确保所有的消息状态都是最新的。
  • 消息状态更新:重放过程中,Broker会检查消息的状态,并确保消息被正确地标记为已发送或已消费。

示例代码

以下是一个简化的伪代码示例,展示了消息如何被写入CommitLog中:

public class Broker {
    private CommitLog commitLog;
    
    public Broker() {
        this.commitLog = new CommitLog();
    }
    
    public void sendToCommitLog(Message message) throws Exception {
        // 将消息写入CommitLog
        long offset = commitLog.appendMessage(message);
        System.out.println("Message stored at offset " + offset);
    }
}

class CommitLog {
    private final int mappedFileSize;
    private final List<MappedFile> mappedFiles;
    
    public CommitLog() {
        this.mappedFileSize = 1 * 1024 * 1024 * 1024; // 1GB
        this.mappedFiles = new ArrayList<>();
        // 初始化MappedFile队列
        this.initializeMappedFiles();
    }
    
    public long appendMessage(Message message) throws Exception {
        MappedFile mappedFile = selectMappedFileToAppend();
        int size = message.getSize();
        return mappedFile.appendMessage(message, size);
    }
    
    private MappedFile selectMappedFileToAppend() {
        if (mappedFiles.isEmpty()) {
            MappedFile mf = new MappedFile(0, mappedFileSize);
            mappedFiles.add(mf);
            return mf;
        } else {
            MappedFile last = mappedFiles.get(mappedFiles.size() - 1);
            if (last.isFull()) {
                MappedFile mf = new MappedFile(last.getFileFromOffset() + mappedFileSize, mappedFileSize);
                mappedFiles.add(mf);
                return mf;
            } else {
                return last;
            }
        }
    }
    
    private void initializeMappedFiles() {
        // 初始化MappedFile队列
        for (int i = 0; i < 5; i++) {
            MappedFile mf = new MappedFile(i * mappedFileSize, mappedFileSize);
            mappedFiles.add(mf);
        }
    }
}

class MappedFile {
    private FileChannel fileChannel;
    private ByteBuffer writeBuffer;
    private long fileFromOffset;
    
    public MappedFile(long fileFromOffset, int fileSize) {
        this.fileFromOffset = fileFromOffset;
        try {
            this.fileChannel = new RandomAccessFile(new File("commitlog_" + fileFromOffset), "rw").getChannel();
            this.writeBuffer = this.fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, fileSize);
        } catch (IOException e) {
            throw new RuntimeException("Failed to create MappedFile", e);
        }
    }
    
    public long appendMessage(Message message, int size) throws Exception {
        // 写入消息
        writeBuffer.put(message.getBody());
        
        // 返回写入的位置
        return fileFromOffset + writeBuffer.position() - size;
    }
    
    public boolean isFull() {
        // 检查MappedFile是否已满
        return writeBuffer.position() >= writeBuffer.capacity();
    }
    
    public long getFileFromOffset() {
        return fileFromOffset;
    }
}

class Message {
    private byte[] body;
    
    public Message(byte[] body) {
        this.body = body;
    }
    
    public int getSize() {
        return body.length;
    }
    
    public byte[] getBody() {
        return body;
    }
}

上述代码是高度简化的,并不包含所有细节。实际的MQ系统会更加复杂,涉及到并发控制、错误处理、数据压缩、数据清理等多种机制。

让我们继续讨论RocketMQ中的CommitLog机制以及消息存储的具体细节。

RocketMQ中的CommitLog机制

在RocketMQ中,CommitLog主要负责持久化消息,并且它是RocketMQ的核心组件之一。下面是一些关键点:

  1. 消息持久化:消息首先被写入到CommitLog中。
  2. 消息索引:为了快速定位消息,RocketMQ维护了一个消息索引文件。
  3. 文件管理CommitLog由一系列MappedFile组成,每个MappedFile通常具有固定的大小(例如1GB)。
  4. 数据刷新:数据可以同步或异步地刷新到磁盘上,以保证数据的持久性。
  5. 消息消费:消费者通过消息索引来定位消息,并从CommitLog中读取消息。

代码示例

接下来,我们将继续上面的示例代码,添加一些额外的功能,如消息索引的创建和消息的读取。

创建消息索引

消息索引文件通常记录每条消息在CommitLog中的起始位置。这里我们简单地添加一个方法来创建消息索引。

class Broker {
    private CommitLog commitLog;
    private ConsumeQueue consumeQueue;

    public Broker() {
        this.commitLog = new CommitLog();
        this.consumeQueue = new ConsumeQueue();
    }
    
    public void sendToCommitLog(Message message) throws Exception {
        // 将消息写入CommitLog
        long offset = commitLog.appendMessage(message);
        
        // 创建消息索引
        consumeQueue.createIndex(message, offset);
        
        System.out.println("Message stored at offset " + offset);
    }
}

class ConsumeQueue {
    private final Map<String, List<ConsumeQueueItem>> indexMap;

    public ConsumeQueue() {
        this.indexMap = new ConcurrentHashMap<>();
    }

    public void createIndex(Message message, long offset) {
        String topic = message.getTopic();
        List<ConsumeQueueItem> items = indexMap.computeIfAbsent(topic, k -> new ArrayList<>());
        items.add(new ConsumeQueueItem(offset, message.getSize()));
    }
}

class ConsumeQueueItem {
    private long offset;
    private int size;

    public ConsumeQueueItem(long offset, int size) {
        this.offset = offset;
        this.size = size;
    }

    public long getOffset() {
        return offset;
    }

    public int getSize() {
        return size;
    }
}
读取消息

消费者可以通过消息索引来定位消息,并从CommitLog中读取消息。这里我们添加一个简单的读取消息的方法。

class Broker {
    private CommitLog commitLog;
    private ConsumeQueue consumeQueue;

    public Broker() {
        this.commitLog = new CommitLog();
        this.consumeQueue = new ConsumeQueue();
    }
    
    public void sendToCommitLog(Message message) throws Exception {
        long offset = commitLog.appendMessage(message);
        consumeQueue.createIndex(message, offset);
        System.out.println("Message stored at offset " + offset);
    }
    
    public Message readMessage(String topic, long offset) throws Exception {
        // 根据topic获取消息索引
        List<ConsumeQueueItem> items = consumeQueue.getIndex(topic);
        
        // 查找指定offset的消息
        ConsumeQueueItem item = items.stream().filter(i -> i.getOffset() == offset).findFirst().orElse(null);
        
        if (item != null) {
            // 从CommitLog中读取消息
            return commitLog.readMessage(item.getOffset(), item.getSize());
        } else {
            throw new RuntimeException("Message not found at offset " + offset);
        }
    }
}

class CommitLog {
    private final int mappedFileSize;
    private final List<MappedFile> mappedFiles;
    
    public CommitLog() {
        this.mappedFileSize = 1 * 1024 * 1024 * 1024; // 1GB
        this.mappedFiles = new ArrayList<>();
        this.initializeMappedFiles();
    }
    
    public long appendMessage(Message message) throws Exception {
        MappedFile mappedFile = selectMappedFileToAppend();
        int size = message.getSize();
        return mappedFile.appendMessage(message, size);
    }
    
    public Message readMessage(long offset, int size) throws Exception {
        // 根据offset找到对应的MappedFile
        MappedFile mappedFile = findMappedFileByOffset(offset);
        return mappedFile.readMessage(offset, size);
    }
    
    private MappedFile selectMappedFileToAppend() {
        if (mappedFiles.isEmpty()) {
            MappedFile mf = new MappedFile(0, mappedFileSize);
            mappedFiles.add(mf);
            return mf;
        } else {
            MappedFile last = mappedFiles.get(mappedFiles.size() - 1);
            if (last.isFull()) {
                MappedFile mf = new MappedFile(last.getFileFromOffset() + mappedFileSize, mappedFileSize);
                mappedFiles.add(mf);
                return mf;
            } else {
                return last;
            }
        }
    }
    
    private MappedFile findMappedFileByOffset(long offset) {
        for (MappedFile mf : mappedFiles) {
            if (mf.getFileFromOffset() <= offset && offset < mf.getFileFromOffset() + mappedFileSize) {
                return mf;
            }
        }
        throw new RuntimeException("MappedFile not found for offset " + offset);
    }
    
    private void initializeMappedFiles() {
        // 初始化MappedFile队列
        for (int i = 0; i < 5; i++) {
            MappedFile mf = new MappedFile(i * mappedFileSize, mappedFileSize);
            mappedFiles.add(mf);
        }
    }
}

class MappedFile {
    private FileChannel fileChannel;
    private ByteBuffer writeBuffer;
    private long fileFromOffset;
    
    public MappedFile(long fileFromOffset, int fileSize) {
        this.fileFromOffset = fileFromOffset;
        try {
            this.fileChannel = new RandomAccessFile(new File("commitlog_" + fileFromOffset), "rw").getChannel();
            this.writeBuffer = this.fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, fileSize);
        } catch (IOException e) {
            throw new RuntimeException("Failed to create MappedFile", e);
        }
    }
    
    public long appendMessage(Message message, int size) throws Exception {
        writeBuffer.put(message.getBody());
        return fileFromOffset + writeBuffer.position() - size;
    }
    
    public Message readMessage(long offset, int size) throws IOException {
        long relativeOffset = offset - fileFromOffset;
        byte[] messageBody = new byte[size];
        writeBuffer.position((int)relativeOffset);
        writeBuffer.get(messageBody);
        return new Message(messageBody);
    }
    
    public boolean isFull() {
        return writeBuffer.position() >= writeBuffer.capacity();
    }
    
    public long getFileFromOffset() {
        return fileFromOffset;
    }
}

注意事项

  • 上述代码是简化的示例,没有涵盖所有细节,例如错误处理、线程安全、文件锁、文件清理等。
  • 实际的RocketMQ源码非常复杂,涉及了大量的并发控制、错误处理、数据压缩、数据清理等机制。
  • RocketMQ中还有一些其他的组件,如ConsumeQueueIndexFile,它们用于进一步优化消息的检索和消费。

希望这些信息和示例代码能够帮助您更好地理解RocketMQ中的CommitLog机制!

😍😍 海量H5小游戏、微信小游戏、Web casualgame源码😍😍
😍😍试玩地址: https://www.bojiogame.sg😍😍
😍看上哪一款,需要源码的csdn私信我😍

————————————————

​最后我们放松一下眼睛
在这里插入图片描述

  • 14
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

极致人生-010

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值