【RocketMQ】消息的刷盘机制

RocketMQ系列5——5.X版本延迟消息 延迟消息5.X版本比4.X版本新增了配置,支持自定义任意延迟时间。延迟消息实现任意时间的任务是基于时间轮做的,时间轮存储定时任务的环形队列,底层采用数组实现,数组中的每一个元素可以存放一个定时任务。 阅读详情

刷盘策略

CommitLog 的 asyncPutMessage 方法中可以看到在写入消息之后,调用了 submitFlushRequest 方法执行刷盘策略:

public class CommitLog {
    public CompletableFuture<PutMessageResult> asyncPutMessage(final MessageExtBrokerInner msg) {
        // ...
        try {
            // 获取上一次写入的文件
            MappedFile mappedFile = this.mappedFileQueue.getLastMappedFile();
            // ...
            // 写入消息
            result = mappedFile.appendMessage(msg, this.appendMessageCallback, putMessageContext);
            // ...
        } finally {
            beginTimeInLock = 0;
            putMessageLock.unlock();
        }
        // ...
        // 执行刷盘
        CompletableFuture<PutMessageStatus> flushResultFuture = submitFlushRequest(result, msg);
        // ...
    }
}

刷盘有两种策略:

  • 同步刷盘,表示消息写入到内存之后需要立刻刷到磁盘文件中。

    同步刷盘会构建 GroupCommitRequest 组提交请求并设置本次刷盘后的位置偏移量的值(写入位置偏移量+写入数据字节数),然后将请求添加到 flushDiskWatcher 和 GroupCommitService 中进行刷盘。

  • 异步刷盘,表示消息写入内存成功之后就返回,由MQ定时将数据刷入到磁盘中,会有一定的数据丢失风险。

public class CommitLog {
    // 监控刷盘
    private final FlushDiskWatcher flushDiskWatcher;
    public CompletableFuture<PutMessageStatus> submitFlushRequest(AppendMessageResult result, MessageExt messageExt) {
        // 是否是同步刷盘
        if (FlushDiskType.SYNC_FLUSH == this.defaultMessageStore.getMessageStoreConfig().getFlushDiskType()) {
            // 获取GroupCommitService
            final GroupCommitService service = (GroupCommitService) this.flushCommitLogService;
            // 是否等待
            if (messageExt.isWaitStoreMsgOK()) {
                // 构建组提交请求,传入本次刷盘后位置的偏移量:写入位置偏移量+写入数据字节数
                GroupCommitRequest request = new GroupCommitRequest(result.getWroteOffset() + result.getWroteBytes(),
                        this.defaultMessageStore.getMessageStoreConfig().getSyncFlushTimeout());
                // 添加到wather中
                flushDiskWatcher.add(request);
                // 添加到service
                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 ,然后构建 GroupCommitRequest 组提交请求,将请求添加到 flushDiskWatcher 和 GroupCommitService 中,其中flushDiskWatcher用于监控刷盘是否超时,GroupCommitService用于提交刷盘数据。

构建GroupCommitRequest提交请求

GroupCommitRequest 是 CommitLog 的内部类:

  • nextOffset :写入位置偏移量+写入数据字节数,也就是本次刷盘成功后应该对应的flush偏移量
  • flushOKFuture :刷盘结果
  • deadLine :刷盘的限定时间,值为当前时间 + 传入的超时时间,超过限定时间还未刷盘完毕会被认为超时
public class CommitLog {
    public static class GroupCommitRequest {
        private final long nextOffset;
        // 刷盘状态
        private CompletableFuture<PutMessageStatus> flushOKFuture = new CompletableFuture<>();
        private final long deadLine;// 刷盘的限定时间,超过限定时间还未刷盘完毕会被认为超时

        public GroupCommitRequest(long nextOffset, long timeoutMillis) {
            this.nextOffset = nextOffset;
            // 设置限定时间:当前时间 + 超时时间
            this.deadLine = System.nanoTime() + (timeoutMillis * 1_000_000);
        }

        public void wakeupCustomer(final PutMessageStatus putMessageStatus) {
            // 结束刷盘,设置刷盘状态
            this.flushOKFuture.complete(putMessageStatus);
        }

        public CompletableFuture<PutMessageStatus> future() {
            // 返回刷盘状态
            return flushOKFuture;
        }

    }
}

GroupCommitService处理刷盘

GroupCommitService 是 CommitLog 的内部类,从继承关系中可知它实现了Runnable接口,在run方法调用 waitForRunning 等待刷盘请求的提交,然后处理刷盘,不过这个线程是在什么时候启动的呢?

public class CommitLog {
    /**
     * GroupCommit Service
     */
    class GroupCommitService extends FlushCommitLogService {
        // ...
        // run方法
        public void run() {
            CommitLog.log.info(this.getServiceName() + " service started");
            while (!this.isStopped()) {
                try {
                    // 等待刷盘请求的到来
                    this.waitForRunning(10);
                    // 处理刷盘
                    this.doCommit();
                } catch (Exception e) {
                    CommitLog.log.warn(this.getServiceName() + " service has exception. ", e);
                }
            }
            // ...
        }
    }
}

刷盘线程的启动

在BrokerController的启动方法中,可以看到调用了 messageStore 的start方法,前面可知使用的是 DefaultMessageStore ,进入到 DefaultMessageStore 的start方法,它又调用了 commitLog 的start方法,在 CommitLog 的 start 方法中,启动了刷盘的线程和监控刷盘的线程:

public class BrokerController {
    public void start() throws Exception {
        if (this.messageStore != null) {
            // 启动
            this.messageStore.start();
        }
        // ...
    }
}

public class DefaultMessageStore implements MessageStore {
   /**
     * @throws Exception
     */
    public void start() throws Exception {
        // ...
        this.flushConsumeQueueService.start();
        // 调用CommitLog的启动方法
        this.commitLog.start();
        this.storeStatsService.start();
        // ...
    }
}

public class CommitLog {
    private final FlushCommitLogService flushCommitLogService; // 刷盘
    private final FlushDiskWatcher flushDiskWatcher; // 监控刷盘
    private final FlushCommitLogService commitLogService; // commitLogService
    public void start() {
        // 启动刷盘的线程
        this.flushCommitLogService.start();
        flushDiskWatcher.setDaemon(true);
        // 启动监控刷盘的线程
        flushDiskWatcher.start();
        if (defaultMessageStore.getMessageStoreConfig().isTransientStorePoolEnable()) {
            this.commitLogService.start();
        }
    }
}

刷盘请求的处理

既然知道了线程在何时启动的,接下来详细看一下 GroupCommitService 是如何处理刷盘提交请求的。

前面知道在 GroupCommitService 的run方法中,调用了 waitForRunning 方法等待刷盘请求, waitForRunning 在 GroupCommitService 父类 ServiceThread 中实现。 ServiceThread 是一个抽象类,实现了Runnable接口, 里面使用了CountDownLatch进行线程间的通信 ,大小设为1。

waitForRunning 方法在进入的时候先判断 hasNotified 是否为true(已通知),并尝试将其更新为false(未通知),由于hasNotified的初始化值为false,所以首次进入的时候条件不成立,不会进入到这个处理逻辑,会继续执行后面的代码。

接着调用 waitPoint的reset方法将其重置为1,并调用waitPoint的await方法进行等待:

// ServiceThread
public abstract class ServiceThread implements Runn
「RocketMQ」消息的刷盘机制 这里使用读写链表进行交换应该是为了提升性能,如果只使用一个链表,在提交请求的时候需要往链表中添加请求,此时需要加锁,而刷盘线程在处理完请求之后是需要从链表中移除请求的,假设添加请求时加的锁还未释放,刷盘线程就要一直等待,而添加和处理完全可以同时进行,所以使用了两个链表,在添加请求的时候使用写链表,处理请求的时候对读写链表的数据进行交换使用读链表,这样只需在交换数据的时候加锁,以此来提升性能。既然知道了线程在何时启动的,接下来详细看一下GroupCommitService是如何处理刷盘提交请求的。 阅读详情

相关推荐

RocketMQ5.0消息存储<四>_刷盘机制

org.apache.rocketmq.store.CommitLog.DefaultFlushManager#handleDiskFlush是刷盘核心方法,含有同步、异步刷盘逻辑,如下代码所示。org.apache.rocketmq.store.CommitLog.FlushManager是刷盘管理器接口,其接口的实现类是org.apache.rocketmq.store.CommitLog.DefaultFlushManager刷盘管理器实现类维护刷盘线程执行周期性刷盘操作。开启堆外内存池的刷盘流程。

专搞技术的小兔子 445

D触发器版图设计的艺术:最小化面积与最大化性能的平衡之道

本文探讨了D触发器版图设计中如何平衡最小化面积与最大化性能的核心挑战。通过分析晶体管布局、互联优化、时钟分布等关键策略,结合先进制程下的功耗与信号完整性考量,为数字IC工程师提供了从基础优化到制造验证的实用解决方案,助力实现高性能、低面积的芯片设计。

aa123的博客 914

STM32驱动HC-SR04超声波模块:两种精准测距方案详解

本文详解STM32驱动HC-SR04超声波模块的两种精准测距方案:定时器中断计数法和外部中断边沿检测法。涵盖硬件连接、代码实现与优化技巧,帮助开发者根据精度和复杂度需求选择合适方案,提升超声波测距在嵌入式项目中的稳定性和准确性。

g5h6i的博客 690

别再乱调栅极电阻了!手把手教你用示波器调试FOC驱动MOS管,避开EMC和震荡坑

本文详细介绍了FOC驱动中MOS管栅极参数的精准调试方法,涵盖示波器配置、波形特征分析及栅极电阻选型策略。通过实战案例和工程经验,帮助工程师有效解决EMC和震荡问题,提升驱动电路稳定性和效率。

weixin_28728495的博客 508

从零玩转显示屏:手把手教你用Arduino驱动SPI屏幕(附引脚定义图)

本文提供了一份详尽的Arduino驱动SPI屏幕的入门指南。从SPI接口的核心引脚定义(如DC、RESET)与RGB接口的区别讲起,手把手指导硬件连接与软件库配置,并最终通过一个天气显示器实战项目,帮助读者掌握驱动SPI屏幕、显示RGB色彩内容的核心技能。

weixin_29189987的博客 136

基于PLC的冲压件自动生产线电气系统设计【附数据】

考虑到生产线的高效运行和维护简便性,选择了三菱FX系列的可编程逻辑控制器(PLC)作为核心控制单元,该型号的PLC因其高可靠性和强大的功能集,在工业自动化领域有着广泛的应用。最后,在完成初步的软件开发后,进行了多轮次的模拟测试和现场调试,逐步修正了存在的问题,最终达到了预期的功能要求。例如,对于进料环节,选用了光电传感器以精确检测物料的位置;此外,为了适应不同尺寸的工件加工需求,还特别设计了一套可调节的夹具系统,不仅提高了生产线的灵活性,同时也降低了更换模具的成本。✅ 感恩科研路上每一位志同道合的伙伴!

lagougongzuoshi的博客 1300

从“破解”到应用:三菱数控系统M80协议逆向分析与工业数据采集网关搭建指南

本文深入解析三菱数控系统M80协议的逆向分析方法与工业数据采集网关搭建技术。通过TCP协议实现跨平台通信,详细介绍了M80协议的数据包结构、多语言实现方案(C#、Java、C/C++)以及Linux数据采集网关的架构设计与容器化部署。为工业自动化领域的开发者提供从协议分析到企业级数据采集落地的完整解决方案。

weixin_29228781的博客 1220

光猫改桥接后,一根网线搞定IPTV和上网的保姆级教程(附VLAN配置避坑点)

本文详细介绍了光猫改桥接后如何通过单线复用技术实现IPTV和上网功能共存。从VLAN配置原理到具体操作步骤,包括光猫超级管理员权限获取、VLAN绑定设置及路由器IPTV功能配置,提供了全面的保姆级教程。特别针对常见问题如IPTV信号丢失、网速下降等给出了实用解决方案,帮助用户轻松避坑。

weixin_29927965的博客 1921

别再被 SerialPort 坑了!C# 串口通信的 3 大隐形陷阱与工业级解决方案

NET的SerialPort类更适合实验室调试,而非工业现场——它的设计目标是“能用”,而非“稳定”。工业级串口通信的核心,是在SerialPort基础上构建一层“防护壳”,用主动轮询对抗事件失效,用硬件级操作解决缓冲区谎言,用原子性流程避免关闭死锁。本文提供的类已在30+工业项目中验证(包括汽车生产线、智能仓储、环境监测),可直接替换原生SerialPort,解决90%以上的“玄学问题”。记住:工业场景的“稳定”,从来都不是靠运气,而是靠对每个细节的偏执把控。

这里只有干货:从 Modbus 通信到 MES 对接,从 YOLO 训练到工控机部署,带你搞定工业软件开发全流程。 754

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

深度学习工具包 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")

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

上一篇: 嵌入式软件架构设计-消息交互
下一篇: 一文聊透 Netty 核心引擎 Reactor 的运转架构
JavaShark
博客等级 码龄5年 184粉丝 438原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址