更新時間:2021-09-17 10:29:56 來源:動力節點 瀏覽2557次
Mycat的事務相關的代碼邏輯,目前的實現方式如下:
用戶會話Session中設定autocommit=false,開啟一個事務過程,這個會話中隨后的所有SQL語句進入事務模式,ServerConnection(前端連接)中有一個變量txInterrupted控制是否事務異常需要回滾
當某個SQL執行過程中發生錯誤,則設置txInterrupted=true,表明此事務需要回滾
當用戶提交事務(commit指令)的時候,Session會檢查事務回滾變量,若發現事務需要回滾,則取消Commit指令在相關節點上的執行過程,返回錯誤信息,Transaction need rollback,用戶只能回滾事務,若所有節點都執行成功,則向每個節點發送Commit指令,事務結束。
從上面的邏輯來看,當前Mycat的事務是一種弱XA的事務,與XA事務相似的地方是,只有所有節點都執行成功(Prepare階段都成功),才開始提交事務,與XA不同的是,在提交階段,若某個節點宕機,沒有手段讓此事務在故障節點恢復以后繼續執行,從實際的概率來說,這個概率也是很小很小的,因此,當前事務的方式還是能滿足絕大數系統對事務的要求。
另外,Mycat當前若XA的事務模式,相對XA還是比較輕量級,性能更好,雖然如此,也不建議一個事務中存在跨多個節點的SQL操作問題,這樣鎖定的資源更多,并發性降低很多。
前端連接中關于事務標記txInterrupted的方法片段:
public class ServerConnection extends FrontendConnection {
/** * 設置是否需要中斷當前事務 */
public void setTxInterrupt(String txInterrputMsg) {
if (!autocommit && !txInterrupted) {
txInterrupted = true;
this.txInterrputMsg = txInterrputMsg;
}
}
public boolean isTxInterrupted() {
return txInterrupted;
}
/** * 提交事務 */
public void commit() {
if (txInterrupted) {
writeErrMessage(ErrorCode.ER_YES,"Transaction error, need to rol lback.");
}else{
session.commit();
}
}
}
SQL出錯時候設置事務回滾標志:
public class SingleNodeHandler implements ResponseHandler, Terminatable,LoadDataResponseHandler {
private void backConnectionErr(ErrorPacket errPkg, BackendConnection conn) {
endRunning();
String errmgs = " errno:" + errPkg.errno + " "+ new String(errPkg.message);
LOGGER.warn("execute sql err :" + errmgs + " con:" + conn);
session.releaseConnectionIfSafe(conn, LOGGER.isDebugEnabled(), false);
ServerConnection source = session.getSource();
source.setTxInterrupt(errmgs);
errPkg.write(source);
recycleResources();
}
}
Session提交事務的關鍵代碼:
public class NonBlockingSession implements Session {
public void commit() {
final int initCount = target.size();
if (initCount <= 0) {
ByteBuffer buffer = source.allocate();
buffer = source.writeToBuffer(OkPacket.OK, buffer); source.write(buffer);
return;
} else if (initCount == 1) {
BackendConnection con = target.elements().nextElement(); commitHandler.commit(con);
} else {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("multi node commit to send ,total " + initCount);
}
multiNodeCoordinator.executeBatchNodeCmd(SQLCmdConstant.COMMIT_CMD);
}
}
}
以上就是對“Mycat的事務管理機制”的介紹,大家如果想了解更多相關知識,可以關注動力節點Mycat教程,文檔當中的內容很詳細,當然也有配套的視頻教程可以免費下載學習,希望對大家能夠有所幫助。
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習