Cet article explore le mécanisme de stockage des messages dans RocketMQ en se basant sur des analyses de code source. Nous examinerons le flux de traitement des requêtes d'envoi de messages, depuis la réception via Netty jusqu'à la persistance sur disque.
Le point d'entrée pour le traitement des messages envoyés est la classe SendMessageProcessor, qui implémente l'interface NettyRequestProcessor.
Le processus de traitement d'une requête d'envoi de message est initié par le module de communication Netty. Voici une vue simplifiée de la chaîne d'appels:
Netty Server -> RemotingAbstract -> SendMessageProcessor.processRequest()
Exmainons le cœur de la méthode sendMessage dans SendMessageProcessor:
private RemotingCommand sendMessage(final ChannelHandlerContext ctx,
final RemotingCommand request,
final SendMessageContext sendMessageContext,
final SendMessageRequestHeader requestHeader) throws RemotingCommandException {
final RemotingCommand response = RemotingCommand.createResponseCommand(SendMessageResponseHeader.class);
final SendMessageResponseHeader responseHeader = (SendMessageResponseHeader) response.readCustomHeader();
response.setOpaque(request.getOpaque());
response.addExtField(MessageConst.PROPERTY_MSG_REGION, this.brokerController.getBrokerConfig().getRegionId());
if (this.brokerController.getMessageStore().now() < this.brokerController.getBrokerConfig().getStartAcceptSendRequestTimeStamp()) {
// Broker is not ready to service requests
response.setCode(ResponseCode.SYSTEM_ERROR);
response.setRemark(String.format("Broker unable to service, until %s", UtilAll.timeMillisToHumanString2(this.brokerController.getBrokerConfig().getStartAcceptSendRequestTimeStamp())));
return response;
}
response.setCode(-1); // Indicate processing in progress
super.msgCheck(ctx, requestHeader, response);
if (response.getCode() != -1) {
return response; // msgCheck detected an issue
}
final byte[] body = request.getBody();
int queueIdInt = requestHeader.getQueueId();
TopicConfig topicConfig = this.brokerController.getTopicConfigManager().selectTopicConfig(requestHeader.getTopic());
if (queueIdInt < 0) {
queueIdInt = Math.abs(this.random.nextInt()) % topicConfig.getWriteQueueNums();
}
int sysFlag = requestHeader.getSysFlag();
if (TopicFilterType.MULTI_TAG == topicConfig.getTopicFilterType()) {
sysFlag |= MessageSysFlag.MultiTagsFlag;
}
String targetTopic = requestHeader.getTopic();
if (targetTopic != null && targetTopic.startsWith(MixAll.RETRY_GROUP_TOPIC_PREFIX)) {
// Handle retry and DLQ topics
String groupName = targetTopic.substring(MixAll.RETRY_GROUP_TOPIC_PREFIX.length());
SubscriptionGroupConfig subscriptionGroupConfig = this.brokerController.getSubscriptionGroupManager().findSubscriptionGroupConfig(groupName);
// ... (logic for retry/DLQ topic handling) ...
if (requestHeader.getReconsumeTimes() != null && requestHeader.getReconsumeTimes() >= subscriptionGroupConfig.getRetryMaxTimes()) {
targetTopic = MixAll.getDLQTopic(groupName);
queueIdInt = Math.abs(this.random.nextInt()) % DLQ_NUMS_PER_GROUP;
topicConfig = this.brokerController.getTopicConfigManager().createTopicInSendMessageBackMethod(targetTopic, DLQ_NUMS_PER_GROUP, PermName.PERM_WRITE, 0);
// ... (error handling for topic creation) ...
}
}
MessageExtBrokerInner msgInner = new MessageExtBrokerInner();
msgInner.setTopic(targetTopic);
msgInner.setBody(body);
msgInner.setFlag(requestHeader.getFlag());
MessageAccessor.setProperties(msgInner, MessageDecoder.string2messageProperties(requestHeader.getProperties()));
msgInner.setPropertiesString(requestHeader.getProperties());
msgInner.setTagsCode(MessageExtBrokerInner.tagsString2tagsCode(topicConfig.getTopicFilterType(), msgInner.getTags()));
msgInner.setQueueId(queueIdInt);
msgInner.setSysFlag(sysFlag);
msgInner.setBornTimestamp(requestHeader.getBornTimestamp());
msgInner.setBornHost(ctx.channel().remoteAddress());
msgInner.setStoreHost(this.getStoreHost());
msgInner.setReconsumeTimes(requestHeader.getReconsumeTimes() == null ? 0 : requestHeader.getReconsumeTimes());
if (this.brokerController.getBrokerConfig().isRejectTransactionMessage()) {
String traFlag = msgInner.getProperty(MessageConst.PROPERTY_TRANSACTION_PREPARED);
if (traFlag != null) {
// Rejecting transaction messages if configured
response.setCode(ResponseCode.NO_PERMISSION);
response.setRemark("Broker sending transaction messages is forbidden");
return response;
}
}
// **** Message Storage Entry Point ****
PutMessageResult putMessageResult = this.brokerController.getMessageStore().putMessage(msgInner);
// **** End Message Storage ****
if (putMessageResult != null) {
boolean sendOK = false;
switch (putMessageResult.getPutMessageStatus()) {
case PUT_OK:
case FLUSH_DISK_TIMEOUT:
case FLUSH_SLAVE_TIMEOUT:
case SLAVE_NOT_AVAILABLE:
sendOK = true;
// Set response code based on status
response.setCode(this.mapPutMessageStatusToResponseCode(putMessageResult.getPutMessageStatus()));
break;
// Handle various failure statuses
case CREATE_MAPEDFILE_FAILED:
response.setCode(ResponseCode.SYSTEM_ERROR);
response.setRemark("create maped file failed, please make sure OS and JDK both 64bit.");
break;
// ... other failure cases ...
default:
response.setCode(ResponseCode.SYSTEM_ERROR);
response.setRemark("UNKNOWN_ERROR");
break;
}
if (sendOK) {
// Update statistics and prepare response header
this.brokerController.getBrokerStatsManager().incTopicPutNums(msgInner.getTopic());
this.brokerController.getBrokerStatsManager().incTopicPutSize(msgInner.getTopic(), putMessageResult.getAppendMessageResult().getWroteBytes());
this.brokerController.getBrokerStatsManager().incBrokerPutNums();
responseHeader.setMsgId(putMessageResult.getAppendMessageResult().getMsgId());
responseHeader.setQueueId(queueIdInt);
responseHeader.setQueueOffset(putMessageResult.getAppendMessageResult().getLogicsOffset());
doResponse(ctx, request, response); // Send response back to client
// Handle SendMessageHook if applicable
// ...
return null; // Request successfully processed, response sent
} else {
// Handle SendMessageHook for failures
// ...
}
} else {
response.setCode(ResponseCode.SYSTEM_ERROR);
response.setRemark("store putMessage return null");
}
return response; // Return response with error code
}
// Helper method to map PutMessageStatus to ResponseCode
private int mapPutMessageStatusToResponseCode(PutMessageStatus status) {
switch (status) {
case PUT_OK: return ResponseCode.SUCCESS;
case FLUSH_DISK_TIMEOUT: return ResponseCode.FLUSH_DISK_TIMEOUT;
case FLUSH_SLAVE_TIMEOUT: return ResponseCode.FLUSH_SLAVE_TIMEOUT;
case SLAVE_NOT_AVAILABLE: return ResponseCode.SLAVE_NOT_AVAILABLE;
default: return ResponseCode.SYSTEM_ERROR; // Should not happen for OK statuses
}
}
Le point d'entrée suivant est la méthode putMessage dans DefaultMessageStore, qui est l'implémentation concrète de l'interface MessageStore.
public PutMessageResult putMessage(MessageExtBrokerInner msg) {
if (this.shutdown) {
// Message store is shut down
return new PutMessageResult(PutMessageStatus.SERVICE_NOT_AVAILABLE, null);
}
if (BrokerRole.SLAVE == this.messageStoreConfig.getBrokerRole()) {
// Cannot write messages in slave mode
if ((this.printTimes.getAndIncrement() % 50000) == 0) {
log.warn("Message store is in slave mode, so putMessage is forbidden");
}
return new PutMessageResult(PutMessageStatus.SERVICE_NOT_AVAILABLE, null);
}
if (!this.runningFlags.isWriteable()) {
// Message store is not writeable
if ((this.printTimes.getAndIncrement() % 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); // Reset counter if writeable
}
// Topic length validation
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);
}
// Properties length validation
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();
// **** Message Storage Execution ****
PutMessageResult result = this.commitLog.putMessage(msg);
// **** End Message Storage ****
// Performance statistics
long eclipseTime = this.getSystemClock().now() - beginTime;
if (eclipseTime > 1000) {
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;
}
La logique principale de stockage se trouve dans la classe CommitLog. La méthode clé est putMessage(final MessageExtBrokerInner msg).
public PutMessageResult putMessage(final MessageExtBrokerInner msg) {
msg.setStoreTimestamp(System.currentTimeMillis());
msg.setBodyCRC(UtilAll.crc32(msg.getBody()));
AppendMessageResult appendResult = null;
StoreStatsService storeStatsService = this.defaultMessageStore.getStoreStatsService();
String topic = msg.getTopic();
int queueId = msg.getQueueId();
final int tranType = MessageSysFlag.getTransactionValue(msg.getSysFlag());
// Handling for delayed messages and schedule topics
if (msg.getDelayTimeLevel() > 0) {
if (msg.getDelayTimeLevel() > this.defaultMessageStore.getScheduleMessageService().getMaxDelayLevel()) {
msg.setDelayTimeLevel(this.defaultMessageStore.getScheduleMessageService().getMaxDelayLevel());
}
topic = ScheduleMessageService.SCHEDULE_TOPIC;
queueId = ScheduleMessageService.delayLevel2QueueId(msg.getDelayTimeLevel());
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;
MapedFile unlockMapedFile = null;
// Get the last mapped file, ensuring exclusive access for writing
MapedFile mapedFile = this.mapedFileQueue.getLastMapedFileWithLock();
synchronized (this) {
long beginLockTimestamp = this.defaultMessageStore.getSystemClock().now();
this.beginTimeInLock = beginLockTimestamp;
msg.setStoreTimestamp(beginLockTimestamp); // Ensure consistent store timestamp
if (null == mapedFile || mapedFile.isFull()) {
mapedFile = this.mapedFileQueue.getLastMapedFile(); // Get the next available file
if (null == mapedFile) {
log.error("create maped file1 error, topic: " + msg.getTopic() + " clientAddr: " + msg.getBornHostString());
return new PutMessageResult(PutMessageStatus.CREATE_MAPEDFILE_FAILED, null);
}
}
// **** Append message to the mapped file ****
appendResult = mapedFile.appendMessage(msg, this.appendMessageCallback);
// **** End Append Message ****
switch (appendResult.getStatus()) {
case PUT_OK:
break;
case END_OF_FILE:
unlockMapedFile = mapedFile; // Mark the current file for unlocking later
mapedFile = this.mapedFileQueue.getLastMapedFile(); // Get a new file
if (null == mapedFile) {
log.error("create maped file2 error, topic: " + msg.getTopic() + " clientAddr: " + msg.getBornHostString());
return new PutMessageResult(PutMessageStatus.CREATE_MAPEDFILE_FAILED, appendResult);
}
appendResult = mapedFile.appendMessage(msg, this.appendMessageCallback); // Append to the new file
break;
case MESSAGE_SIZE_EXCEEDED:
case PROPERTIES_SIZE_EXCEEDED:
return new PutMessageResult(PutMessageStatus.MESSAGE_ILLEGAL, appendResult);
default:
return new PutMessageResult(PutMessageStatus.UNKNOWN_ERROR, appendResult);
}
eclipseTimeInLock = this.defaultMessageStore.getSystemClock().now() - beginLockTimestamp;
this.beginTimeInLock = 0; // Reset lock timestamp
} // End synchronized block
if (eclipseTimeInLock > 1000) {
log.warn("[NOTIFYME]putMessage in lock cost time(ms)={}, bodyLength={} AppendMessageResult={}", eclipseTimeInLock, msg.getBody().length, appendResult);
}
// Unlock the previous file if it was full and a new one was created
if (null != unlockMapedFile) {
this.defaultMessageStore.unlockMapedFile(unlockMapedFile);
}
PutMessageResult putMessageResult = new PutMessageResult(PutMessageStatus.PUT_OK, appendResult);
// Statistics update
storeStatsService.getSinglePutMessageTopicTimesTotal(msg.getTopic()).incrementAndGet();
storeStatsService.getSinglePutMessageTopicSizeTotal(topic).addAndGet(appendResult.getWroteBytes());
// ---- Disk Flush Handling ----
GroupCommitRequest request = null;
// Synchronous flush
if (FlushDiskType.SYNC_FLUSH == this.defaultMessageStore.getMessageStoreConfig().getFlushDiskType()) {
GroupCommitService service = (GroupCommitService) this.flushCommitLogService;
if (msg.isWaitStoreMsgOK()) {
request = new GroupCommitRequest(appendResult.getWroteOffset() + appendResult.getWroteBytes());
service.putRequest(request);
boolean flushOK = request.waitForFlush(this.defaultMessageStore.getMessageStoreConfig().getSyncFlushTimeout());
if (!flushOK) {
log.error("do groupcommit, wait for flush failed...");
putMessageResult.setPutMessageStatus(PutMessageStatus.FLUSH_DISK_TIMEOUT);
}
} else {
service.wakeup(); // Wake up the flush thread
}
}
// Asynchronous flush
else {
this.flushCommitLogService.wakeup(); // Wake up the flush thread for async flush
}
// ---- HA (High Availability) Handling ----
if (BrokerRole.SYNC_MASTER == this.defaultMessageStore.getMessageStoreConfig().getBrokerRole()) {
HAService haService = this.defaultMessageStore.getHaService();
if (msg.isWaitStoreMsgOK()) {
if (haService.isSlaveOK(appendResult.getWroteOffset() + appendResult.getWroteBytes())) {
if (null == request) { // Create if not already created for sync flush
request = new GroupCommitRequest(appendResult.getWroteOffset() + appendResult.getWroteBytes());
}
haService.putRequest(request);
haService.getWaitNotifyObject().wakeupAll();
boolean flushOK = request.waitForFlush(this.defaultMessageStore.getMessageStoreConfig().getSyncFlushTimeout());
if (!flushOK) {
log.error("do sync transfer other node, wait return, but failed...");
putMessageResult.setPutMessageStatus(PutMessageStatus.FLUSH_SLAVE_TIMEOUT);
}
} else {
putMessageResult.setPutMessageStatus(PutMessageStatus.SLAVE_NOT_AVAILABLE); // Slave is not available
}
}
}
return putMessageResult;
}
La méthode appendMessage dans MapedFile est responsable de l'écriture réelle des données dans le buffer mémoire.
/**
* Inserts a message into a MappedFile and returns the result.
* A MappedFile can be understood as a memory buffer for a file. Data is written to the buffer before being flushed to disk, similar to NIO.
* @param msg The message to append.
* @param cb The callback for appending the message.
* @return The result of the append operation.
*/
public AppendMessageResult appendMessage(final Object msg, final AppendMessageCallback cb) {
assert msg != null;
assert cb != null;
int currentPosition = this.wrotePosition.get();
if (currentPosition < this.fileSize) {
// Get the byte buffer to write to. The check for writeBuffer != null and using different buffers is related to FlushCommitLogService.
ByteBuffer byteBuffer = this.mappedByteBuffer.slice();
byteBuffer.position(currentPosition);
// **** Execute the append callback ****
AppendMessageResult result = cb.doAppend(this.getFileFromOffset(), byteBuffer, this.fileSize - currentPosition, msg);
// **** End Append Callback ****
this.wrotePosition.addAndGet(result.getWroteBytes());
this.storeTimestamp = result.getStoreTimestamp();
return result;
}
log.error("MapedFile.appendMessage return null, wrotePosition: " + currentPosition + " fileSize: " + this.fileSize);
return new AppendMessageResult(AppendMessageStatus.UNKNOWN_ERROR);
}
Le cœur de l'écriture se trouve dans la méthode doAppend du AppendMessageCallback (qui est une instance de CommitLog).
public AppendMessageResult doAppend(final long fileFromOffset, final ByteBuffer byteBuffer, final int maxBlank, final Object msg) {
MessageExtBrokerInner msgInner = (MessageExtBrokerInner) msg;
// Calculate the physical offset in the commit log
long wroteOffset = fileFromOffset + byteBuffer.position();
String msgId = MessageDecoder.createMessageId(this.msgIdMemory, msgInner.getStoreHostBytes(), wroteOffset);
// Manage ConsumeQueue information (topic-queue offset mapping)
String key = msgInner.getTopic() + "-" + msgInner.getQueueId();
Long queueOffset = CommitLog.this.topicQueueTable.get(key);
if (null == queueOffset) {
queueOffset = 0L;
CommitLog.this.topicQueueTable.put(key, queueOffset);
}
// Handle transaction message types (Prepared/Rollback are not consumed)
final int tranType = MessageSysFlag.getTransactionValue(msgInner.getSysFlag());
switch (tranType) {
case MessageSysFlag.TransactionPreparedType:
case MessageSysFlag.TransactionRollbackType:
queueOffset = 0L; // Reset queue offset for these types
break;
default:
break;
}
// Serialize message properties and topic
final byte[] propertiesData = msgInner.getPropertiesString() == null ? null : msgInner.getPropertiesString().getBytes(MessageDecoder.CHARSET_UTF8);
if (propertiesData.length > Short.MAX_VALUE) {
log.warn("putMessage message properties length too long. length={}", propertiesData.length);
return new AppendMessageResult(AppendMessageStatus.PROPERTIES_SIZE_EXCEEDED);
}
final short propertiesLength = propertiesData == null ? 0 : (short) propertiesData.length;
final byte[] topicData = msgInner.getTopic().getBytes(MessageDecoder.CHARSET_UTF8);
final int topicLength = topicData == null ? 0 : topicData.length;
final int bodyLength = msgInner.getBody() == null ? 0 : msgInner.getBody().length;
final int msgLen = calMsgLength(bodyLength, topicLength, propertiesLength);
// Check if message exceeds maximum allowed size
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);
}
// Check if there is enough space in the current mapped file
if ((msgLen + END_FILE_MIN_BLANK_LENGTH) > maxBlank) {
// Not enough space, mark as end of file and prepare for a new mapped file
this.resetMsgStoreItemMemory(maxBlank);
this.msgStoreItemMemory.putInt(maxBlank); // TOTALSIZE
this.msgStoreItemMemory.putInt(CommitLog.BlankMagicCode); // MAGICCODE
// Fill remaining space with arbitrary data
byteBuffer.put(this.msgStoreItemMemory.array(), 0, maxBlank);
return new AppendMessageResult(AppendMessageStatus.END_OF_FILE, wroteOffset, maxBlank, msgId, msgInner.getStoreTimestamp(), queueOffset, CommitLog.this.defaultMessageStore.now() - beginTimeMills);
}
// Initialize memory buffer for the message
this.resetMsgStoreItemMemory(msgLen);
// Populate the buffer with message fields
this.msgStoreItemMemory.putInt(msgLen); // 1 TOTALSIZE
this.msgStoreItemMemory.putInt(CommitLog.MessageMagicCode); // 2 MAGICCODE
this.msgStoreItemMemory.putInt(msgInner.getBodyCRC()); // 3 BODYCRC
this.msgStoreItemMemory.putInt(msgInner.getQueueId()); // 4 QUEUEID
this.msgStoreItemMemory.putInt(msgInner.getFlag()); // 5 FLAG
this.msgStoreItemMemory.putLong(queueOffset); // 6 QUEUEOFFSET
this.msgStoreItemMemory.putLong(fileFromOffset + byteBuffer.position()); // 7 PHYSICALOFFSET
this.msgStoreItemMemory.putInt(msgInner.getSysFlag()); // 8 SYSFLAG
this.msgStoreItemMemory.putLong(msgInner.getBornTimestamp()); // 9 BORNTIMESTAMP
this.msgStoreItemMemory.put(msgInner.getBornHostBytes()); // 10 BORNHOST
this.msgStoreItemMemory.putLong(msgInner.getStoreTimestamp()); // 11 STORETIMESTAMP
this.msgStoreItemMemory.put(msgInner.getStoreHostBytes()); // 12 STOREHOSTADDRESS
this.msgStoreItemMemory.putInt(msgInner.getReconsumeTimes()); // 13 RECONSUMETIMES
this.msgStoreItemMemory.putLong(msgInner.getPreparedTransactionOffset()); // 14 Prepared Transaction Offset
this.msgStoreItemMemory.putInt(bodyLength); // 15 BODY length
if (bodyLength > 0) this.msgStoreItemMemory.put(msgInner.getBody()); // 15 BODY data
this.msgStoreItemMemory.put((byte) topicLength); // 16 TOPIC length
this.msgStoreItemMemory.put(topicData); // 16 TOPIC data
this.msgStoreItemMemory.putShort(propertiesLength); // 17 PROPERTIES length
if (propertiesLength > 0) this.msgStoreItemMemory.put(propertiesData); // 17 PROPERTIES data
// **** Write the serialized message to the mappedByteBuffer ****
byteBuffer.put(this.msgStoreItemMemory.array(), 0, msgLen);
// **** End Write ****
AppendMessageResult result = new AppendMessageResult(AppendMessageStatus.PUT_OK, wroteOffset, msgLen, msgId, msgInner.getStoreTimestamp(), queueOffset, CommitLog.this.defaultMessageStore.now() - beginTimeMills);
// Update topic-queue offset mapping for transactional messages
switch (tranType) {
case MessageSysFlag.TransactionPreparedType:
case MessageSysFlag.TransactionRollbackType:
break;
case MessageSysFlag.TransactionNotType:
case MessageSysFlag.TransactionCommitType:
CommitLog.this.topicQueueTable.put(key, ++queueOffset); // Increment for next message
break;
default:
break;
}
return result;
}
Le MappedByteBuffer est une représentation d'un fichier mappé en mémoire, fournie par NIO. Il est initialisé dans le constructeur de MapedFile.
Après que le message a été écrit dans le MappedByteBuffer, le processus de "flush" (persistance sur disque) est déclenché. Cela se produit dans la méthode sendMessage, via le service FlushCommitLogService, qui peut fonctionner en mode synchrone ou asynchrone selon la configuration FlushDiskType.
Pour le flush synchrone, le service GroupCommitService est utilisé. Sa méthode doCommit appelle MapedFileQueue.commit().
// Inside GroupCommitService.doCommit()
if (!this.requestsRead.isEmpty()) {
for (GroupCommitRequest req : this.requestsRead) {
boolean flushOK = false;
// Try flushing up to two pages to ensure the commit offset is reached
for (int i = 0; (i < 2) && !flushOK; i++) {
flushOK = (CommitLog.this.mapedFileQueue.getCommittedWhere() >= req.getNextOffset());
if (!flushOK) {
CommitLog.this.mapedFileQueue.commit(0); // Force commit
}
}
req.wakeupCustomer(flushOK); // Notify the waiting producer
}
long storeTimestamp = CommitLog.this.mapedFileQueue.getStoreTimestamp();
if (storeTimestamp > 0) {
CommitLog.this.defaultMessageStore.getStoreCheckpoint().setPhysicMsgTimestamp(storeTimestamp);
}
this.requestsRead.clear();
} else {
// If no requests, still commit to advance the committed position
CommitLog.this.mapedFileQueue.commit(0);
}
La classe MapedFileQueue gère une collection de MapedFile, représentant les différents fichiers de données sur disque. La méthode commit(final int flushLeastPages) est essentielle pour la persistance.
public boolean commit(final int flushLeastPages) {
boolean result = true;
// Find the mapped file corresponding to the committed offset
MapedFile mapedFile = this.findMapedFileByOffset(this.committedWhere, true);
if (mapedFile != null) {
long tmpTimeStamp = mapedFile.getStoreTimestamp();
// **** Force flush the mapped file to disk ****
int offset = mapedFile.commit(flushLeastPages);
// **** End Force Flush ****
long where = mapedFile.getFileFromOffset() + offset;
result = (where == this.committedWhere);
this.committedWhere = where; // Update the global committed offset
if (0 == flushLeastPages) {
this.storeTimestamp = tmpTimeStamp;
}
}
return result;
}
La méthode commit(final int flushLeastPages) dans MapedFile exécute le flush disque réel.
/**
* Flushes the message to disk.
* @param flushLeastPages Minimum number of pages to flush.
* @return The current committed position.
*/
public int commit(final int flushLeastPages) {
// Check if flushing is possible based on available pages
if (this.isAbleToFlush(flushLeastPages)) {
// Use a reference count mechanism to manage concurrent flushes
if (this.hold()) {
int value = this.wrotePosition.get(); // Get the current write position
// **** Force the mappedByteBuffer to sync with disk ****
this.mappedByteBuffer.force();
// **** End Force Flush ****
this.committedPosition.set(value); // Update the committed position
this.release(); // Release the reference count
} else {
log.warn("in commit, hold failed, commit offset = " + this.committedPosition.get());
this.committedPosition.set(this.wrotePosition.get()); // Ensure committed position is updated
}
}
return this.getCommittedPosition();
}
Les fichiers de données sont stockés dans des instances de MapedFileQueue, qui est initialisée lors de la construction de CommitLog. La méthode load() de MapedFileQueue charge les fichiers existanst au démarrage.
// Inside MapedFileQueue.load()
public boolean load() {
File dir = new File(this.storePath);
File[] files = dir.listFiles();
if (files != null) {
Arrays.sort(files); // Load files in ascending order
for (File file : files) {
if (file.length() != this.mapedFileSize) {
log.warn(file + "\t" + file.length() + " length not matched message store config value, ignore it");
continue; // Skip files with incorrect size
}
try {
// **** Create a new MapedFile instance ****
MapedFile mapedFile = new MapedFile(file.getPath(), mapedFileSize);
// **** End MapedFile Instance Creation ****
mapedFile.setWrotePostion(this.mapedFileSize); // Set initial positions
mapedFile.setCommittedPosition(this.mapedFileSize);
this.mapedFiles.add(mapedFile);
log.info("load " + file.getPath() + " OK");
} catch (IOException e) {
log.error("load file " + file + " error", e);
return false; // Indicate failure
}
}
}
return true; // Successfully loaded
}
Le constructeur de MapedFile initialise le FileChannel et mappe le fichier en mémoire via MappedByteBuffer.
// Inside MapedFile constructor
public MapedFile(final String fileName, final int fileSize) throws IOException {
// ...
try {
// **** Get FileChannel and map the file ****
this.fileChannel = new RandomAccessFile(this.file, "rw").getChannel();
this.mappedByteBuffer = this.fileChannel.map(MapMode.READ_WRITE, 0, fileSize);
// **** End Mapping ****
TotalMapedVitualMemory.addAndGet(fileSize);
TotalMapedFiles.incrementAndGet();
ok = true;
} catch (FileNotFoundException e) {
log.error("create file channel " + this.fileName + " Failed. ", e);
throw e;
} catch (IOException e) {
log.error("map file " + this.fileName + " Failed. ", e);
throw e;
} finally {
if (!ok && this.fileChannel != null) {
this.fileChannel.close();
}
}
}