Broker 在收到Producer发送过来的消息后,会存入CommitLog对应的内存映射区中,见CommitLog类的putMessage方法。该方法执行OK后,会判断存储配置中刷盘模式:同步or异步?继而进行对应的操作。 
ServiceThread –> FlushCommitLogService 
–> GroupCommitService 
–> FlushRealTimeService

// Synchronization flush, 默认是异步刷盘
if (FlushDiskType.SYNC_FLUSH == this.defaultMessageStore.getMessageStoreConfig().getFlushDiskType()) {
GroupCommitService service = (GroupCommitService) this.flushCommitLogService;
if (msg.isWaitStoreMsgOK()) {
request = new GroupCommitRequest(result.getWroteOffset() + result.getWroteBytes());
//
service.putRequest(request);
boolean flushOK =
request.waitForFlush(this.defaultMessageStore.getMessageStoreConfig()
.getSyncFlushTimeout());
if (!flushOK) {
log.error("do groupcommit, wait for flush failed, topic: " + msg.getTopic() + " tags: "
+ msg.getTags() + " client address: " + msg.getBornHostString());
putMessageResult.setPutMessageStatus(PutMessageStatus.FLUSH_DISK_TIMEOUT);
}
}
else {
service.wakeup();
}
}
// Asynchronous flush
else {
this.flushCommitLogService.wakeup();
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

可以看到,对于同步刷盘而言,会构造一个GroupCommitRequest对象,表明从哪里写,写多少字节。然后等待刷盘工作的完成。对于异步刷盘而言,只是notify()异步刷盘任务这个Runnable,对于何时执行真正写磁盘操作,要看线程调度了。

同步刷盘逻辑:从上面可以看到,给GroupCommitService Runnable 传递了一个GroupCommitRequest对象,触发的逻辑是会唤醒这个刷盘线程:

public void putRequest(final GroupCommitRequest request) {
synchronized (this) {
this.requestsWrite.add(request);
if (!this.hasNotified) {
this.hasNotified = true;
this.notify();
}
}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

接下来,waitForFlush()会一直等到执行刷盘操作的完成。

public boolean waitForFlush(long timeout) {
try {
// 当刷盘完成后会调用 countDownLatch.countDown()
boolean result = this.countDownLatch.await(timeout, TimeUnit.MILLISECONDS);
return result || this.flushOK;
}
catch (InterruptedException e) {
e.printStackTrace();
return false;
}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

那么是如何保证同步等待这个过程的完成呢?CountDownLatch,闭锁这个同步工具可以保证线程达到某种状态后才会继续下去,所以线程总是会运行的,执行刷盘操作。

 private void doCommit() {
if (!this.requestsRead.isEmpty()) {
for (GroupCommitRequest req : this.requestsRead) {
// There may be a message in the next file, so a maximum of
// two times the flush
boolean flushOK = false;
for (int i = 0; (i < 2) && !flushOK; i++) {
flushOK = (CommitLog.this.mapedFileQueue.getCommittedWhere() >= req.getNextOffset()); if (!flushOK) {
CommitLog.this.mapedFileQueue.commit(0);
}
} req.wakeupCustomer(flushOK);
} long storeTimestamp = CommitLog.this.mapedFileQueue.getStoreTimestamp();
if (storeTimestamp > 0) {
CommitLog.this.defaultMessageStore.getStoreCheckpoint().setPhysicMsgTimestamp(
storeTimestamp);
}
//注意这里清空了,所以保证写时为空
this.requestsRead.clear();
}
else {
// Because of individual messages is set to not sync flush, it
// will come to this process
CommitLog.this.mapedFileQueue.commit(0);
}
} public void run() {
while (!this.isStoped()) {
try { // 等待时机唤醒,然后执行flush操作
this.waitForRunning(0);
this.doCommit();
}
catch (Exception e) {//.. }
}
// 下面是线程正常终止,处理逻辑
// Under normal circumstances shutdown, wait for the arrival of the
// request, and then flush
try {
Thread.sleep(10);
}
catch (InterruptedException e) {
CommitLog.log.warn("GroupCommitService Exception, ", e);
} synchronized (this) {
this.swapRequests();
} this.doCommit();
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56

刷盘完成后,调用wakeupCustomer(),改变闭锁状态,刷盘完成。

 public void wakeupCustomer(final boolean flushOK) {
this.flushOK = flushOK;
this.countDownLatch.countDown();
}
  • 1
  • 2
  • 3
  • 4

*异步刷盘的逻辑:从上面可以看到,对于异步刷盘,只是唤醒了该实时刷盘线程。假以时日,定会运行。异步刷盘又可以设置为定时或者实时,默认是实时。

public void run() {
while (!this.isStoped()) {
// 是否定时方式刷盘,默认是实时刷盘real time
boolean flushCommitLogTimed =
CommitLog.this.defaultMessageStore.getMessageStoreConfig().isFlushCommitLogTimed();
// CommitLog刷盘间隔时间 default 1s
int interval =
CommitLog.this.defaultMessageStore.getMessageStoreConfig()
.getFlushIntervalCommitLog();
// 刷CommitLog,至少刷几个PAGE default 4
int flushPhysicQueueLeastPages =
CommitLog.this.defaultMessageStore.getMessageStoreConfig()
.getFlushCommitLogLeastPages();
// 刷CommitLog,彻底刷盘间隔时间 default 10s
int flushPhysicQueueThoroughInterval =
CommitLog.this.defaultMessageStore.getMessageStoreConfig()
.getFlushCommitLogThoroughInterval();
try {
if (flushCommitLogTimed) {
Thread.sleep(interval);
}
else {// 实时刷,等待消息写入mapped area的通知
this.waitForRunning(interval);
}
// 进行刷盘
CommitLog.this.mapedFileQueue.commit(flushPhysicQueueLeastPages);
long storeTimestamp = CommitLog.this.mapedFileQueue.getStoreTimestamp();
if (storeTimestamp > 0) {
CommitLog.this.defaultMessageStore.getStoreCheckpoint().setPhysicMsgTimestamp(
storeTimestamp);
}
}
catch (Exception e) {//.... }
} // Normal shutdown, to ensure that all the flush before exit
//如果线程是正常终止 就要保证所有mapped area中数据写到磁盘 所以参数是0
boolean result = false;
for (int i = 0; i < RetryTimesOver && !result; i++) {
result = CommitLog.this.mapedFileQueue.commit(0);
CommitLog.log.info(this.getServiceName() + " service shutdown, retry " + (i + 1) + " times "
+ (result ? "OK" : "Not OK"));
}
CommitLog.log.info(this.getServiceName() + " service end");
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45

committedWhere(long类型)变量记录写到映射区的数据字节数,据此取模可以定位到具体的一个Commitlog文件,然后写入(具体后面),写入完成后更新状态变量committedWhere

 public boolean commit(final int flushLeastPages) {
boolean result = true;
MapedFile mapedFile = this.findMapedFileByOffset(this.committedWhere, true);
if (mapedFile != null) {
long tmpTimeStamp = mapedFile.getStoreTimestamp();
//
int offset = mapedFile.commit(flushLeastPages);
long where = mapedFile.getFileFromOffset() + offset;
result = (where == this.committedWhere);
// 更新 Commit Log写到了哪里
this.committedWhere = where;
if (0 == flushLeastPages) {
this.storeTimestamp = tmpTimeStamp;
}
} return result;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

判断是否符合刷盘条件

 // 是否符合刷盘条件:映射文件满 or 数据满足指定的least page
private boolean isAbleToFlush(final int flushLeastPages) {
int flush = this.committedPosition.get();
int write = this.wrotePostion.get(); // 如果当前文件已经写满,应该立刻刷盘
if (this.isFull()) {
return true;
} // 只有未刷盘数据满足指定page数目才刷盘
if (flushLeastPages > 0) {
return ((write / OS_PAGE_SIZE) - (flush / OS_PAGE_SIZE)) >= flushLeastPages;
} // flushLeastPages 有数据就flush
return write > flush;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

实际的Flush映射内存区中的数据到物理设备中

 public int commit(final int flushLeastPages) {
if (this.isAbleToFlush(flushLeastPages)) {
if (this.hold()) {
int value = this.wrotePostion.get();
this.mappedByteBuffer.force();//写入存储设备
this.committedPosition.set(value);
this.release();
}
else {
//..
}
}
return this.getCommittedPosition();
}

mq刷盘方式的更多相关文章

  1. Rocket重试机制,消息模式,刷盘方式

    一.Consumer 批量消费(推模式) 可以通过 consumer.setConsumeMessageBatchMaxSize(10);//每次拉取10条 这里需要分为2种情况 Consumer端先 ...

  2. rocketmq刷盘过程

     本文基于rocketmq4.0版本,结合CommitlLog的刷盘过程,对消息队列的刷盘过程源码进行分析,进而对RocketMQ的刷盘原理和过程进行了解.   rocketmq 4.0版本中刷盘类型 ...

  3. RocketMQ中Broker的刷盘源码分析

    上一篇博客的最后简单提了下CommitLog的刷盘  [RocketMQ中Broker的消息存储源码分析] (这篇博客和上一篇有很大的联系) Broker的CommitLog刷盘会启动一个线程,不停地 ...

  4. 【mq读书笔记】mq索引文件刷盘

    索引文件的刷盘并不是采取定时刷盘机制,而是每更新一次索引文件就会将上一次的改动刷写到磁盘. 同步刷盘: GroupCommitRequest将被提交到GroupCommitService线程,Grou ...

  5. RocketMQ消息丢失解决方案:同步刷盘+手动提交

    前言 之前我们一起了解了使用RocketMQ事务消息解决生产者发送消息时消息丢失的问题,但使用了事务消息后消息就一定不会丢失了吗,肯定是不能保证的. 因为虽然我们解决了生产者发送消息时候的消息丢失问题 ...

  6. 【RocketMQ】消息的刷盘机制

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

  7. MySQL InnoDB 日志管理机制中的MTR和日志刷盘

    1.MTR(mini-transaction) 在MySQL的 InnoDB日志管理机制中,有一个很重要的概念就是MTR.MTR是InnoDB存储擎中一个很重要的用来保证物理写的完整性和持久性的机制. ...

  8. Centos系统真机安装,U盘方式

    下载Centos系统镜像,建议选择Minimal ISO.下载地址:https://www.centos.org/download/ 下载Fedora Media Writer,用来将系统镜像写到U盘 ...

  9. LeetCode 到底怎么刷?GitHub 上多位大厂程序员亲测的高效刷题方式

    作者:HelloGitHub-小鱼干 在众多的诸如阿里.腾讯等大厂之中,最看中面试者刷题技能的大概要数有"链表厂"之称的字节跳动了.作为一个新晋大厂,字节跳动以高薪.技术大佬云集吸 ...

随机推荐

  1. Ubuntu Touch On Nexus4 Manual Install (手动安装) under Gentoo

    Table of Contents 1. 准备工作: 2. Saucy Salamander 3. 刷入 最新 版Touch 最近手里的 Nexus 4 手机一直闲置,它的配置要比我六年前买的笔记本还 ...

  2. hdu 5120(求两个圆环相交的面积 2014北京现场赛 I题)

    两个圆环的内外径相同 给出内外径 和 两个圆心 求两个圆环相交的面积 画下图可以知道 就是两个大圆交-2*小圆与大圆交+2小圆交 Sample Input22 30 00 02 30 05 0 Sam ...

  3. hdu 5131 (2014广州现场赛 E题)

    题意:对给出的好汉按杀敌数从大到小排序,若相等,按字典序排.M个询问,询问名字输出对应的主排名和次排名.(排序之后)主排名是在该名字前比他杀敌数多的人的个数加1,次排名是该名字前和他杀敌数相等的人的个 ...

  4. PHP随机浮点数

    function randomFloat($min = 0, $max = 1) { $rand = mt_rand(); $lmax = mt_getrandmax(); return $min + ...

  5. phpmyadmin新加用户登陆不了,测试解决方案。

    今天在给项目配置数据库管理平台时遇到一个问题,不论怎么添加mysql用户在登陆phpmyadmin时始终无法登陆,不管准不准许为空依然报出#1045 无法登陆服务器的错误,最后打开mysql库中use ...

  6. PLSQL Developer个性化设置

    1)代码自动完成 和讨厌的.才后出现提示说88,我用快捷键任意呼唤. Tools->Preferences->User Interface->Key Configuration.找到 ...

  7. PHP经典算法百钱买小鸡

    遇到一道有趣的题,并计算2种方法的效率,发现如果穷举所有组合竟高达1000000次排列~所以简化到了600次.所以,你的一个条件,或者一个运算,可能会提高几千倍的效率! <?php header ...

  8. 在 Pandas 中更改列的数据类型

    import pandas as pd import numpy as np a = [['a', '1.2', '4.2'], ['b', '70', '0.03'], ['x', '5', '0' ...

  9. MySQL大事务导致的Insert慢的案例分析

    [问题] 有台MySQL服务器不定时的会出现并发线程的告警,从记录信息来看,有大量insert的慢查询,执行几十秒,等待flushing log,状态query end [初步分析] 从等待资源来看, ...

  10. MSTP多生成树的配置

    STP的不足 STP协议虽然能够解决环路问题,但是由于网络拓扑收敛较慢,影响了用户通信质量 而且如果网络中的拓扑结构频繁变化,网络也会随之频繁失去连通性,从而导致用户通信频繁中断 RSTP对STP的改 ...