主頁 > 後端開發 > 通過原始碼分析RocketMQ主從復制原理

通過原始碼分析RocketMQ主從復制原理

2023-03-03 07:14:33 後端開發

作者:京東物流 宮丙來

一、主從復制概述

  • RocketMQ Broker的主從復制主要包括兩部分內容:CommitLog的訊息復制和Broker元資料的復制,

  • CommitLog的訊息復制是發生在訊息寫入時,當訊息寫完Broker Master時,會通過單獨的執行緒,將訊息寫入到從服務器,在寫入的時候支持同步寫入、異步寫入兩種方式,

  • Broker元資料的寫入,則是Broker從服務器通過單獨的執行緒每隔10s從主Broker上獲取,然后更新從的配置,并持久化到相應的組態檔中,

  • RocketMQ主從同步一個重要的特征:主從同步不具備主從切換功能,即當主節點宕機后,從不會接管訊息發送,但可以提供訊息讀取,

二、CommitLog訊息復制

2.1、整體概述

CommitLog主從復制的流程如下:

1.Producer發送訊息到Broker Master,Broker進行訊息存盤,并呼叫handleHA進行主從同步;
2.如果是同步復制的話,參考2.6章節的同步復制;
3.如果是異步復制的話,流程如下:

1. Broker Master啟動,并在指定埠監聽;
2. Broker Slave啟動,主動連接Broker Master,通過Java NIO建立TCP連接;
3.  Broker Slave以每隔5s的間隔時間向服務端拉取訊息,如果是第一次拉取的話,先獲取本地CommitLog檔案中最大的偏移量,以該偏移量向服務端拉取訊息
4.  Broker Master 決議請求,并回傳資料給Broker Slave;
5.Broker Slave收到一批訊息后,將訊息寫入本地CommitLog檔案中,然后向Master匯報拉取進度,并更新下一次待拉取偏移量;

我們先看下異步復制的整體流程,最后再看下同步復制的流程,異步復制的入口為HAService.start();

public void start() throws Exception {
 //broker master啟動,接收slave請求,并處理
    this.acceptSocketService.beginAccept();
    this.acceptSocketService.start();
 //同步復制執行緒啟動
    this.groupTransferService.start();
 //broker slave啟動
    this.haClient.start();
}

下面分別對上面的每一步做詳細說明,

2.2、HAService Master啟動

public void beginAccept() throws Exception {
    this.serverSocketChannel = ServerSocketChannel.open();
    this.selector = RemotingUtil.openSelector();
    this.serverSocketChannel.socket().setReuseAddress(true);
    this.serverSocketChannel.socket().bind(this.socketAddressListen);
    this.serverSocketChannel.configureBlocking(false);
    this.serverSocketChannel.register(this.selector, SelectionKey.OP_ACCEPT);
}

在beginAccept方法中主要創建了ServerSocketChannel、Selector、設定TCP reuseAddress、系結監聽埠、設定為非阻塞模式,并注冊OP_ACCEPT(連接事件),可以看到在這里是通過Java原生的NIO來實作的,并沒有通過Netty框架來實作,

acceptSocketService.start()啟動方法代碼如下:

while (!this.isStopped()) {
    try {
   //獲取事件
        this.selector.select(1000);
        Set<SelectionKey> selected = this.selector.selectedKeys();
        if (selected != null) {
            for (SelectionKey k : selected) {
//處理OP_ACCEPT事件,并創建HAConnection
                if ((k.readyOps() & SelectionKey.OP_ACCEPT) != 0) {
                    SocketChannel sc = ((ServerSocketChannel) k.channel()).accept();
                    if (sc != null) {
                       HAConnection conn = new HAConnection(HAService.this, sc);
                       //主要是啟動readSocketService,writeSocketService這兩個執行緒
 conn.start();
                       HAService.this.addConnection(conn);
                    }
                }
            }
            selected.clear();
        }
    } catch (Exception e) {
        log.error(this.getServiceName() + " service has exception.", e);
    }
}

選擇器每1s處理一次處理一次連接就緒事件,連接事件就緒后,呼叫ServerSocketChannel的accept()方法創建SocketChannel,與服務端資料傳輸的通道,然后為每一個連接創建一個HAConnection物件,該HAConnection將負責Master-Slave資料同步邏輯,HAConnection.start方法如下:

public void start() {
	this.readSocketService.start();
	this.writeSocketService.start();
}

2.3、HAClient啟動

while (!this.isStopped()) {
	try {
		//和broker master建立連接,通過java nio來實作
		if (this.connectMaster()) {
			//在心跳的同時,上報offset
			if (this.isTimeToReportOffset()) {
				//上報offset
				boolean result = this.reportSlaveMaxOffset(this.currentReportedOffset);
				if (!result) {
					this.closeMaster();
				}
			}
			this.selector.select(1000);
			//處理網路讀請求,也就是處理從Master傳回的訊息資料
			boolean ok = this.processReadEvent();
			if (!ok) {
				this.closeMaster();
			}
			if (!reportSlaveMaxOffsetPlus()) {
				continue;
			}
			long interval =
				HAService.this.getDefaultMessageStore().getSystemClock().now()
					- this.lastWriteTimestamp;
			if (interval > HAService.this.getDefaultMessageStore().getMessageStoreConfig()
				.getHaHousekeepingInterval()) {
				log.warn("HAClient, housekeeping, found this connection[" + this.masterAddress
					+ "] expired, " + interval);
				this.closeMaster();
				log.warn("HAClient, master not response some time, so close connection");
			}
		} else {
			this.waitForRunning(1000 * 5);
		}
	} catch (Exception e) {
		log.warn(this.getServiceName() + " service has exception. ", e);
		this.waitForRunning(1000 * 5);
	}
}

2.3.1、HAService主從建立連接

如果socketChannel為空,則嘗試連接Master,如果Master地址為空,回傳false,

private boolean connectMaster() throws ClosedChannelException {
	if (null == socketChannel) {
		String addr = this.masterAddress.get();
		if (addr != null) {
			SocketAddress socketAddress = RemotingUtil.string2SocketAddress(addr);
			if (socketAddress != null) {
				this.socketChannel = RemotingUtil.connect(socketAddress);
				if (this.socketChannel != null) {
					//注冊讀事件,監聽broker master回傳的資料
					this.socketChannel.register(this.selector, SelectionKey.OP_READ);
				}
			}
		}
		//獲取當前的offset
		this.currentReportedOffset = HAService.this.defaultMessageStore.getMaxPhyOffset();
		this.lastWriteTimestamp = System.currentTimeMillis();
	}
	return this.socketChannel != null;
}
  1. Broker 主從連接

Broker Slave通過NIO來進行Broker Master連接,代碼如下:

SocketChannel sc = null;
sc = SocketChannel.open();
sc.configureBlocking(true);
sc.socket().setSoLinger(false, -1);
sc.socket().setTcpNoDelay(true);
sc.socket().setReceiveBufferSize(1024 * 64);
sc.socket().setSendBufferSize(1024 * 64);
sc.socket().connect(remote, timeoutMillis);
sc.configureBlocking(false);
  1. Slave獲取當前offset
public long getMaxPhyOffset() {
	return this.commitLog.getMaxOffset();
}
public long getMaxOffset() {
	return this.mappedFileQueue.getMaxOffset();
}
public long getMaxOffset() {
	MappedFile mappedFile = getLastMappedFile();
	if (mappedFile != null) {
		return mappedFile.getFileFromOffset() + mappedFile.getReadPosition();
	}
	return 0;
}

可以看到最侄訓是通過讀取MappedFile的position來獲取從的offset,

2.3.2、上報offset時間判斷

private boolean isTimeToReportOffset() {
	//當前時間-上次寫的時間
	long interval =
		HAService.this.defaultMessageStore.getSystemClock().now() - this.lastWriteTimestamp;
	boolean needHeart = interval > HAService.this.defaultMessageStore.getMessageStoreConfig()
		.getHaSendHeartbeatInterval();


	return needHeart;
}

判斷邏輯為當前時間-上次寫的時間>haSendHeartbeatInterval時,則進行心跳和offset的上報,haSendHeartbeatInterval默認為5s,可配置,

2.3.3、上報offset

private boolean reportSlaveMaxOffset(final long maxOffset) {
	this.reportOffset.position(0);
	this.reportOffset.limit(8);
	this.reportOffset.putLong(maxOffset);
	this.reportOffset.position(0);
	this.reportOffset.limit(8);
	//最多發送三次,reportOffset是否有剩余
	for (int i = 0; i < 3 && this.reportOffset.hasRemaining(); i++) {
		try {
			this.socketChannel.write(this.reportOffset);
		} catch (IOException e) {
			log.error(this.getServiceName()
				+ "reportSlaveMaxOffset this.socketChannel.write exception", e);
			return false;
		}
	}
	return !this.reportOffset.hasRemaining();
}

主要還是通過NIO發送請求,

2.4、Broker Master處理請求

在主從建立連接時創建了HAConnection物件,該物件主要包含了如下兩個重要的執行緒服務類:

//負責寫,將commitlog資料發送到從
private WriteSocketService writeSocketService;
//負責讀,讀取從上報的offset,并根據offset從Broker Master讀取commitlog
private ReadSocketService readSocketService;

2.4.1、ReadSocketService接收讀請求

readSocketService.run方法如下:

while (!this.isStopped()) {
	try {
		this.selector.select(1000);
		//處理讀事件
		boolean ok = this.processReadEvent();
		if (!ok) {
			HAConnection.log.error("processReadEvent error");
			break;
		}
		long interval = HAConnection.this.haService.getDefaultMessageStore().getSystemClock().now() - this.lastReadTimestamp;
		if (interval > HAConnection.this.haService.getDefaultMessageStore().getMessageStoreConfig().getHaHousekeepingInterval()) {
			log.warn("ha housekeeping, found this connection[" + HAConnection.this.clientAddr + "] expired, " + interval);
			break;
		}
	} catch (Exception e) {
		HAConnection.log.error(this.getServiceName() + " service has exception.", e);
		break;
	}
}

processReadEvent的邏輯如下:

int readSize = this.socketChannel.read(this.byteBufferRead);
if (readSize > 0) {
	readSizeZeroTimes = 0;
	this.lastReadTimestamp = HAConnection.this.haService.getDefaultMessageStore().getSystemClock().now();
	if ((this.byteBufferRead.position() - this.processPostion) >= 8) {
		int pos = this.byteBufferRead.position() - (this.byteBufferRead.position() % 8);
		//獲取slave 請求的offset
		long readOffset = this.byteBufferRead.getLong(pos - 8);
		this.processPostion = pos;


		HAConnection.this.slaveAckOffset = readOffset;
		if (HAConnection.this.slaveRequestOffset < 0) {
			HAConnection.this.slaveRequestOffset = readOffset;
			log.info("slave[" + HAConnection.this.clientAddr + "] request offset " + readOffset);
		}
		//如果是同步復制的話,判斷請求的offset是否push2SlaveMaxOffset相同,相同的話則喚醒master GroupTransferService
		HAConnection.this.haService.notifyTransferSome(HAConnection.this.slaveAckOffset);
	}
}

可以看到processReadEvent邏輯很簡單,就是從ByteBuffer中決議出offset,然后設定HAConnection.this.slaveRequestOffset;

2.4.2、WriteSocketService進行寫處理

Broker Master通過HAConnection.WriteSocketService進行CommitLog的讀取,run方法主邏輯如下:

this.selector.select(1000);
//nextTransferFromWhere下次傳輸commitLog的起始位置
if (-1 == this.nextTransferFromWhere) {
	if (0 == HAConnection.this.slaveRequestOffset) {
		long masterOffset = HAConnection.this.haService.getDefaultMessageStore().getCommitLog().getMaxOffset();
		masterOffset =
			masterOffset
				- (masterOffset % HAConnection.this.haService.getDefaultMessageStore().getMessageStoreConfig()
				.getMapedFileSizeCommitLog());


		if (masterOffset < 0) {
			masterOffset = 0;
		}


		this.nextTransferFromWhere = masterOffset;
	} else {
		this.nextTransferFromWhere = HAConnection.this.slaveRequestOffset;
	}


	log.info("master transfer data from " + this.nextTransferFromWhere + " to slave[" + HAConnection.this.clientAddr
		+ "], and slave request " + HAConnection.this.slaveRequestOffset);
}


//獲取commitLog資料
SelectMappedBufferResult selectResult = HAConnection.this.haService.getDefaultMessageStore().getCommitLogData(this.nextTransferFromWhere);
//獲取commitLog資料
SelectMappedBufferResult selectResult =
	HAConnection.this.haService.getDefaultMessageStore().getCommitLogData(this.nextTransferFromWhere);
if (selectResult != null) {
	int size = selectResult.getSize();
	if (size > HAConnection.this.haService.getDefaultMessageStore().getMessageStoreConfig().getHaTransferBatchSize()) {
		size = HAConnection.this.haService.getDefaultMessageStore().getMessageStoreConfig().getHaTransferBatchSize();
	}


	long thisOffset = this.nextTransferFromWhere;
	this.nextTransferFromWhere += size;


	selectResult.getByteBuffer().limit(size);
	this.selectMappedBufferResult = selectResult;


	// Build Header
	this.byteBufferHeader.position(0);
	this.byteBufferHeader.limit(headerSize);
	this.byteBufferHeader.putLong(thisOffset);
	this.byteBufferHeader.putInt(size);
	this.byteBufferHeader.flip();
	//nio發送commitlog
	this.lastWriteOver = this.transferData();
} else {
    //如果沒有獲取到commitLog資料,等待100ms
	HAConnection.this.haService.getWaitNotifyObject().allWaitForRunning(1

這里面主要包括獲取CommitLog資料、發送CommitLog資料這兩個步驟,

2.4.2.1、獲取CommitLog資料

public SelectMappedBufferResult getData(final long offset, final boolean returnFirstOnNotFound) {
	int mappedFileSize = this.defaultMessageStore.getMessageStoreConfig().getMapedFileSizeCommitLog();
	MappedFile mappedFile = this.mappedFileQueue.findMappedFileByOffset(offset, returnFirstOnNotFound);
	if (mappedFile != null) {
		int pos = (int) (offset % mappedFileSize);
		SelectMappedBufferResult result = mappedFile.selectMappedBuffer(pos);
		return result;
	}
	return null;
}
public SelectMappedBufferResult selectMappedBuffer(int pos) {
	int readPosition = getReadPosition();
	if (pos < readPosition && pos >= 0) {
		if (this.hold()) {
			ByteBuffer byteBuffer = this.mappedByteBuffer.slice();
			byteBuffer.position(pos);
			int size = readPosition - pos;
			ByteBuffer byteBufferNew = byteBuffer.slice();
			byteBufferNew.limit(size);
			return new SelectMappedBufferResult(this.fileFromOffset + pos, byteBufferNew, size, this);
		}
	}
	return null;
}

可以看到最侄訓是根據offset從MappedFile讀取資料,

2.4.2.2、發送CommitLog資料

資料主要包括header、body兩部分,資料發送的話還是通過NIO來實作,主要代碼如下:

// Build Header
this.byteBufferHeader.position(0);
this.byteBufferHeader.limit(headerSize);
this.byteBufferHeader.putLong(thisOffset);
this.byteBufferHeader.putInt(size);
this.byteBufferHeader.flip();


int writeSize = this.socketChannel.write(this.byteBufferHeader);
// Write Body
if (!this.byteBufferHeader.hasRemaining()) {
	while (this.selectMappedBufferResult.getByteBuffer().hasRemaining()) {
		int writeSize = this.socketChannel.write(this.selectMappedBufferResult.getByteBuffer());
		if (writeSize > 0) {
			writeSizeZeroTimes = 0;
			this.lastWriteTimestamp = HAConnection.this.haService.getDefaultMessageStore().getSystemClock().now();
		} else if (writeSize == 0) {
			if (++writeSizeZeroTimes >= 3) {
				break;
			}
		} else {
			throw new Exception("ha master write body error < 0");
		}
	}
}

CommitLog主從發送完成后,Broker Slave則會監聽讀事件、獲取CommitLog資料,并進行CommitLog的寫入,

2.5、HAClient processReadEvent

在主從建立連接后,從注冊了可讀事件,目的就是讀取從Broker Master回傳的CommitLog資料,對應的方法為HAClient.processReadEvent:

int readSize = this.socketChannel.read(this.byteBufferRead);
if (readSize > 0) {
	lastWriteTimestamp = HAService.this.defaultMessageStore.getSystemClock().now();
	readSizeZeroTimes = 0;
	boolean result = this.dispatchReadRequest();
	if (!result) {
		log.error("HAClient, dispatchReadRequest error");
		return false;
	}
} 

dispatchReadRequest方法如下:

 //讀取回傳的body data
byte[] bodyData = https://www.cnblogs.com/Jcloud/p/new byte[bodySize];
this.byteBufferRead.position(this.dispatchPostion + msgHeaderSize);
this.byteBufferRead.get(bodyData);


HAService.this.defaultMessageStore.appendToCommitLog(masterPhyOffset, bodyData);


this.byteBufferRead.position(readSocketPos);
this.dispatchPostion += msgHeaderSize + bodySize;


//上報從的offset
if (!reportSlaveMaxOffsetPlus()) {
	return false;

里面的核心邏輯主要包括如下三個步驟:

  1. 從byteBufferRead中讀取CommitLog資料;
  1. 呼叫defaultMessageStore.appendToCommitLog方法,將資料寫入到MappedFile檔案,寫入方法如下:
public boolean appendToCommitLog(long startOffset, byte[] data) {
	//將資料寫到commitlog,同普通訊息的存盤
	boolean result = this.commitLog.appendData(startOffset, data);
	//喚醒reputMessageService,構建consumeQueue,index
	this.reputMessageService.wakeup();
	return result;
}
  1. 上報從新的offset,也是讀取MappedFile的offset,然后上報Broker Master;

2.6、同步復制

上面主要介紹了Broker的異步復制,下面再來看下Broker的同步復制的實作,同步復制的整體流程圖如下:


大概說明如下:

  1. producer發送訊息到broker,broker進行訊息的存盤,將訊息寫入到commitLog;

  2. broker master寫訊息執行緒喚醒WriteSocketService執行緒,查詢commitLog資料,然后發送到從,在WriteSocketService獲取commitLog時,如果沒有獲取到commitLog資料,會等待100ms,所以當commitLog新寫入資料的時候,會喚醒WriteSocketService,然后查詢commitLog資料,發送到從,

  3. broker master創建GroupCommitRequest,同步等待主從復制完成;

  4. 從接受新的commitLog資料,然后寫commitLog資料,并回傳新的slave offset到主;

  5. 主更新push2SlaveMaxOffset,并判斷push2SlaveMaxOffset是否大于等于主從復制請求的offset,如果大于等于的話,則認為主從復制完成,回傳commitLog.handleHA方法成功,從而回傳訊息保存成功,

對應的代碼入口為CommitLog.handleHA方法,

public void handleHA(AppendMessageResult result, PutMessageResult putMessageResult, MessageExt messageExt) {
	//如果是broker主,并且是同步復制的話
	if (BrokerRole.SYNC_MASTER == this.defaultMessageStore.getMessageStoreConfig().getBrokerRole()) {
		//獲取HAService
		HAService service = this.defaultMessageStore.getHaService();
		//獲取Message上的MessageConst.PROPERTY_WAIT_STORE_MSG_OK,默認是需要等待主從復制完成
		if (messageExt.isWaitStoreMsgOK()) {
			/**
			 * 判斷從是否可用,判斷的邏輯是:(主offset-push2SlaveMaxOffset<1024 * 1024 * 256),也就是如果主從的offset差的太多,
			 * 則認為從不可用, Tell the producer, slave not available
			 * 這里的result = mappedFile.appendMessage(msg, this.appendMessageCallback);
			 */
			if (service.isSlaveOK(result.getWroteOffset() + result.getWroteBytes())) {
				//組裝GroupCommitRequest,nextOffset=result.getWroteOffset() + result.getWroteBytes(),這里的nextOffset指的就是從要寫到的offset
				GroupCommitRequest request = new GroupCommitRequest(result.getWroteOffset() + result.getWroteBytes());
				                    /**
                * 呼叫的是this.groupTransferService.putRequest(request);將request放到requestsWrite list中,
                  * HAService持有GroupTransferService groupTransferService參考;
                */
				service.putRequest(request);
				 /**
                     * 喚醒的是WriteSocketService,查詢commitLog資料,然后發送到從,
                     * 在WriteSocketService獲取commitLog時,如果沒有獲取到commitLog資料,等待100ms
                     * HAConnection.this.haService.getWaitNotifyObject().allWaitForRunning(100);
                     * 所以當commitLog新寫入資料的時候,會喚醒WriteSocketService,然后查詢commitLog資料,發送到從,
                     */
				service.getWaitNotifyObject().wakeupAll();


				//等待同步復制完成,判斷邏輯是: HAService.this.push2SlaveMaxOffset.get() >= req.getNextOffset();
				boolean flushOK =
					request.waitForFlush(this.defaultMessageStore.getMessageStoreConfig().getSyncFlushTimeout());


				//如果同步復制失敗的話,設定putMessageResult中的狀態為同步從超時
				if (!flushOK) {
					log.error("do sync transfer other node, wait return, but failed, topic: " + messageExt.getTopic() + " tags: "
						+ messageExt.getTags() + " client address: " + messageExt.getBornHostNameString());
					putMessageResult.setPutMessageStatus(PutMessageStatus.FLUSH_SLAVE_TIMEOUT);
				}
			}
			// Slave problem
			else {
				// Tell the producer, slave not available
				putMessageResult.setPutMessageStatus(PutMessageStatus.SLAVE_NOT_AVAILABLE);
			}
		}
	}

2.6.1、GroupTransferService啟動

在HAService啟動的時候,啟動了GroupTransferService執行緒,代碼如下:

public void run() {
	while (!this.isStopped()) {
		this.waitForRunning(10);
		this.doWaitTransfer();
	}
}
private void doWaitTransfer() {
	synchronized (this.requestsRead) {
		if (!this.requestsRead.isEmpty()) {
			for (CommitLog.GroupCommitRequest req : this.requestsRead) {
				/**
				 * req.getNextOffset:result.getWroteOffset() + result.getWroteBytes()
				 * push2SlaveMaxOffset:
				 */
				boolean transferOK = HAService.this.push2SlaveMaxOffset.get() >= req.getNextOffset();
				//在這回圈5次,最多等待5s,因為slave 心跳間隔默認5s
				for (int i = 0; !transferOK && i < 5; i++) {
					this.notifyTransferObject.waitForRunning(1000);
					transferOK = HAService.this.push2SlaveMaxOffset.get() >= req.getNextOffset();
				}
				if (!transferOK) {
					log.warn("transfer messsage to slave timeout, " + req.getNextOffset());
				}
				//主從復制完成,喚醒handleHA后續操作
                req.wakeupCustomer(transferOK);
			}
			this.requestsRead.clear();
		}
	}
}

wakeupCustomer:

public void wakeupCustomer(final boolean flushOK) {
    this.flushOK = flushOK;
    this.countDownLatch.countDown();
}

2.6.2、喚醒WriteSocketService

service.getWaitNotifyObject().wakeupAll();

喚醒的是WriteSocketService,查詢commitLog資料,然后發送到從,在WriteSocketService獲取commitLog時,如果沒有獲取到commitLog資料,等待100ms,HAConnection.this.haService.getWaitNotifyObject().allWaitForRunning(100);所以當commitLog新寫入資料的時候,會喚醒WriteSocketService,然后查詢commitLog資料,發送到從,

2.6.3、同步等待,直到復制完成

boolean flushOK =
	request.waitForFlush(this.defaultMessageStore.getMessageStoreConfig().getSyncFlushTimeout());


public boolean waitForFlush(long timeout) {
	try {
		//等待同步復制完成
		this.countDownLatch.await(timeout, TimeUnit.MILLISECONDS);
		return this.flushOK;
	} catch (InterruptedException e) {
		log.error("Interrupted", e);
		return false;
	}
}
}

三、元資料的復制

broker元資料的復制,主要包括topicConfig、consumerOffset、delayOffset、subscriptionGroup這幾部分,整體流程圖如下:


從broker通過單獨的執行緒,每隔10s進行一次元資料的復制 ,代碼入口為:BrokerController.start -> SlaveSynchronize.syncAll:

slaveSyncFuture = this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
    @Override
    public void run() {
        try {
            //10s 進行一次主從同步
            BrokerController.this.slaveSynchronize.syncAll();
        }
        catch (Throwable e) {
            log.error("ScheduledTask SlaveSynchronize syncAll error.", e);
        }
    }
}, 1000 * 3, 1000 * 10, TimeUnit.MILLISECONDS);


public void syncAll() {
    this.syncTopicConfig();
    this.syncConsumerOffset();
    this.syncDelayOffset();
    this.syncSubscriptionGroupConfig();
}

3.1、syncTopicConfig

//從Master獲取TopicConfig資訊,最終呼叫的是AdminBrokerProcessor.getAllTopicConfig
TopicConfigSerializeWrapper topicWrapper =
    this.brokerController.getBrokerOuterAPI().getAllTopicConfig(masterAddrBak);
if (!this.brokerController.getTopicConfigManager().getDataVersion()
    .equals(topicWrapper.getDataVersion())) {
    this.brokerController.getTopicConfigManager().getDataVersion()
        .assignNewOne(topicWrapper.getDataVersion());
    this.brokerController.getTopicConfigManager().getTopicConfigTable().clear();
    this.brokerController.getTopicConfigManager().getTopicConfigTable()
        .putAll(topicWrapper.getTopicConfigTable());
 //將topicConfig進行持久化,對應的檔案為topics.json
    this.brokerController.getTopicConfigManager().persist();
    log.info("Update slave topic config from master, {}", masterAddrBak)

3.2、syncConsumerOffset

//從"主Broker"獲取ConsumerOffset
ConsumerOffsetSerializeWrapper offsetWrapper =
        this.brokerController.getBrokerOuterAPI().getAllConsumerOffset(masterAddrBak);
//設定從的offsetTable
this.brokerController.getConsumerOffsetManager().getOffsetTable()
                    .putAll(offsetWrapper.getOffsetTable());
//并持久化到從的consumerOffset.json檔案中
this.brokerController.getConsumerOffsetManager().persist(); 

3.3、syncDelayOffset

String delayOffset = this.brokerController.getBrokerOuterAPI().getAllDelayOffset(masterAddrBak);
String fileName = StorePathConfigHelper.getDelayOffsetStorePath(this.brokerController
.getMessageStoreConfig().getStorePathRootDir());
 MixAll.string2File(delayOffset, fileName);

3.4、syncSubscriptionGroupConfig

SubscriptionGroupWrapper subscriptionWrapper =this.brokerController.getBrokerOuterAPI().getAllSubscriptionGroupConfig(masterAddrBak);
SubscriptionGroupManager subscriptionGroupManager =this.brokerController.getSubscriptionGroupManager();
subscriptionGroupManager.getDataVersion().assignNewOne(subscriptionWrapper.getDataVersion());
subscriptionGroupManager.getSubscriptionGroupTable().clear();
subscriptionGroupManager.getSubscriptionGroupTable().putAll(subscriptionWrapper.getSubscriptionGroupTable());
subscriptionGroupManager.persist();

四、思考與識訓

通過上面的分享,我們基本上了解了RocketMQ的主從復制原理,其中有些思想我們可以后續借鑒下:

  1. 在功能設計的時候將元資料、程式資料分開管理;

  2. 主從復制的時候,基本思想都是從請求主,請求時帶上offset,然后主查詢資料回傳從,從再執行;mysql的主從復制、redis的主從復制基本也是這樣;

  3. 主從復制包括異步復制、同步復制兩種方式,可以通過配置來決定使用哪種同步方式,這個需要根據實際業務場景來決定;

  4. 主從復制執行緒盡量和訊息寫執行緒或者主執行緒分開;

由于時間、精力有限,難免會有紕漏、考慮不到之處,如有問題歡迎溝通、交流,

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/545518.html

標籤:Java

上一篇:用GoRoutines高性能同時進行多個Api呼叫

下一篇:springboot后端接收不到前端傳來的表單值

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • Rust中的智能指標:Box<T> Rc<T> Arc<T> Cell<T> RefCell<T> Weak

    Rust中的智能指標是什么 智能指標(smart pointers)是一類資料結構,是擁有資料所有權和額外功能的指標。是指標的進一步發展 指標(pointer)是一個包含記憶體地址的變數的通用概念。這個地址參考,或 ” 指向”(points at)一些其 他資料 。參考以 & 符號為標志并借用了他們所 ......

    uj5u.com 2023-04-20 07:24:10 more
  • Java的值傳遞和參考傳遞

    值傳遞不會改變本身,參考傳遞(如果傳遞的值需要實體化到堆里)如果發生修改了會改變本身。 1.基本資料型別都是值傳遞 package com.example.basic; public class Test { public static void main(String[] args) { int ......

    uj5u.com 2023-04-20 07:24:04 more
  • [2]SpinalHDL教程——Scala簡單入門

    第一個 Scala 程式 shell里面輸入 $ scala scala> 1 + 1 res0: Int = 2 scala> println("Hello World!") Hello World! 檔案形式 object HelloWorld { /* 這是我的第一個 Scala 程式 * 以 ......

    uj5u.com 2023-04-20 07:23:58 more
  • 理解函式指標和回呼函式

    理解 函式指標 指向函式的指標。比如: 理解函式指標的偽代碼 void (*p)(int type, char *data); // 定義一個函式指標p void func(int type, char *data); // 宣告一個函式func p = func; // 將指標p指向函式func ......

    uj5u.com 2023-04-20 07:23:52 more
  • Django筆記二十五之資料庫函式之日期函式

    本文首發于公眾號:Hunter后端 原文鏈接:Django筆記二十五之資料庫函式之日期函式 日期函式主要介紹兩個大類,Extract() 和 Trunc() Extract() 函式作用是提取日期,比如我們可以提取一個日期欄位的年份,月份,日等資料 Trunc() 的作用則是截取,比如 2022-0 ......

    uj5u.com 2023-04-20 07:23:45 more
  • 一天吃透JVM面試八股文

    什么是JVM? JVM,全稱Java Virtual Machine(Java虛擬機),是通過在實際的計算機上仿真模擬各種計算機功能來實作的。由一套位元組碼指令集、一組暫存器、一個堆疊、一個垃圾回收堆和一個存盤方法域等組成。JVM屏蔽了與作業系統平臺相關的資訊,使得Java程式只需要生成在Java虛擬機 ......

    uj5u.com 2023-04-20 07:23:31 more
  • 使用Java接入小程式訂閱訊息!

    更新完微信服務號的模板訊息之后,我又趕緊把微信小程式的訂閱訊息給實作了!之前我一直以為微信小程式也是要企業才能申請,沒想到小程式個人就能申請。 訊息推送平臺🔥推送下發【郵件】【短信】【微信服務號】【微信小程式】【企業微信】【釘釘】等訊息型別。 https://gitee.com/zhongfuch ......

    uj5u.com 2023-04-20 07:22:59 more
  • java -- 緩沖流、轉換流、序列化流

    緩沖流 緩沖流, 也叫高效流, 按照資料型別分類: 位元組緩沖流:BufferedInputStream,BufferedOutputStream 字符緩沖流:BufferedReader,BufferedWriter 緩沖流的基本原理,是在創建流物件時,會創建一個內置的默認大小的緩沖區陣列,通過緩沖 ......

    uj5u.com 2023-04-20 07:22:49 more
  • Java-SpringBoot-Range請求頭設定實作視頻分段傳輸

    老實說,人太懶了,現在基本都不喜歡寫筆記了,但是網上有關Range請求頭的文章都太水了 下面是抄的一段StackOverflow的代碼...自己大修改過的,寫的注釋挺全的,應該直接看得懂,就不解釋了 寫的不好...只是希望能給視頻網站開發的新手一點點幫助吧. 業務場景:視頻分段傳輸、視頻多段傳輸(理 ......

    uj5u.com 2023-04-20 07:22:42 more
  • Windows 10開發教程_編程入門自學教程_菜鳥教程-免費教程分享

    教程簡介 Windows 10開發入門教程 - 從簡單的步驟了解Windows 10開發,從基本到高級概念,包括簡介,UWP,第一個應用程式,商店,XAML控制元件,資料系結,XAML性能,自適應設計,自適應UI,自適應代碼,檔案管理,SQLite資料庫,應用程式到應用程式通信,應用程式本地化,應用程式 ......

    uj5u.com 2023-04-20 07:22:35 more