二十、spring事務(wù)之回滾事務(wù)

Spring事務(wù)信息準(zhǔn)備好后,如果我們的程序出現(xiàn)了異常,又會(huì)如何回滾事務(wù)呢?這節(jié)我們分析Spring事務(wù)回滾原理。
TransactionAspectSupport#invokeWithinTransaction方法中部分代碼塊

    try {
    // This is an around advice: Invoke the next interceptor in the chain.
    // This will normally result in a target object being invoked.
    //執(zhí)行業(yè)務(wù)邏輯
    retVal = invocation.proceedWithInvocation();
    }
    catch (Throwable ex) {
    // target invocation exception
    completeTransactionAfterThrowing(txInfo, ex);
    throw ex;
    }

當(dāng)執(zhí)行業(yè)務(wù)邏輯拋出異常后,調(diào)用completeTransactionAfterThrowing方法回滾事務(wù),這里得注意的是,如果程序不把異常拋出,而且捕獲異常,Spring是不會(huì)回滾的。

protected void completeTransactionAfterThrowing(TransactionInfo txInfo, Throwable ex) {
    //判斷是否存在事務(wù)
    if (txInfo != null && txInfo.hasTransaction()) {
        if (logger.isTraceEnabled()) {
            logger.trace("Completing transaction for [" + txInfo.getJoinpointIdentification() +
                    "] after exception: " + ex);
        }
        //根據(jù)異常類型判斷是否回滾,可以通過Transactional注解中rollbackFor、rollbackForClassName、noRollbackForClassName配置
        if (txInfo.transactionAttribute.rollbackOn(ex)) {
            try {
                //處理回滾
                txInfo.getTransactionManager().rollback(txInfo.getTransactionStatus());
            }
            catch (TransactionSystemException ex2) {
                logger.error("Application exception overridden by rollback exception", ex);
                ex2.initApplicationException(ex);
                throw ex2;
            }
            catch (RuntimeException ex2) {
                logger.error("Application exception overridden by rollback exception", ex);
                throw ex2;
            }
            catch (Error err) {
                logger.error("Application exception overridden by rollback error", ex);
                throw err;
            }
        }
        else {
            // We don't roll back on this exception.
            // Will still roll back if TransactionStatus.isRollbackOnly() is true.
            //如果不滿足符合的異常類型,也同樣會(huì)提交
            try {
                txInfo.getTransactionManager().commit(txInfo.getTransactionStatus());
            }
            catch (TransactionSystemException ex2) {
                logger.error("Application exception overridden by commit exception", ex);
                ex2.initApplicationException(ex);
                throw ex2;
            }
            catch (RuntimeException ex2) {
                logger.error("Application exception overridden by commit exception", ex);
                throw ex2;
            }
            catch (Error err) {
                logger.error("Application exception overridden by commit error", ex);
                throw err;
            }
        }
    }
}

回滾邏輯如下:

  1. 判斷是否存在事務(wù),只有存在事務(wù)才執(zhí)行回滾
  2. 根據(jù)異常類型判斷是否回滾。如果異常類型不符合,仍然會(huì)提交事務(wù)
  3. 回滾處理

詳細(xì)分析每個(gè)步驟

回滾條件

txInfo.transactionAttribute.rollbackOn(ex)

TransactionInfo中的TransactionAttribute屬性值的是RuleBasedTransactionAttribute,在解析@Transactional注解時(shí)初始化,它的rollbackOn方法實(shí)現(xiàn)如下:

@Override
public boolean rollbackOn(Throwable ex) {
    if (logger.isTraceEnabled()) {
        logger.trace("Applying rules to determine whether transaction should rollback on " + ex);
    }

    RollbackRuleAttribute winner = null;
    int deepest = Integer.MAX_VALUE;

    //rollbackRules保存@Transactional注解中rollbackFor、rollbackForClassName、noRollbackForClassName配置的值
    if (this.rollbackRules != null) {
        for (RollbackRuleAttribute rule : this.rollbackRules) {
            int depth = rule.getDepth(ex);
            if (depth >= 0 && depth < deepest) {
                deepest = depth;
                winner = rule;
            }
        }
    }

    if (logger.isTraceEnabled()) {
        logger.trace("Winning rollback rule is: " + winner);
    }

    // User superclass behavior (rollback on unchecked) if no rule matches.
    //若@Transactional沒有配置,默認(rèn)調(diào)用父類的
    if (winner == null) {
        logger.trace("No relevant rollback rule found: applying default rules");
        return super.rollbackOn(ex);
    }

    return !(winner instanceof NoRollbackRuleAttribute);
}

//super
@Override
public boolean rollbackOn(Throwable ex) {
    return (ex instanceof RuntimeException || ex instanceof Error);
}

判斷是否能夠回滾的邏輯如下:
(1) 根據(jù)@Transactional注解中rollbackFor、rollbackForClassName、noRollbackForClassName配置的值,找到最符合ex的異常類型,如果符合的異常類型不是NoRollbackRuleAttribute,則可以執(zhí)行回滾。
(2) 如果@Transactional沒有配置,則默認(rèn)使用RuntimeException和Error異常。

回滾處理

txInfo.getTransactionManager().rollback(txInfo.getTransactionStatus());

交給事務(wù)管理器回滾事務(wù)。

private void processRollback(DefaultTransactionStatus status) {
    try {
        try {
            triggerBeforeCompletion(status);
            //如果有安全點(diǎn),回滾至安全點(diǎn)
            if (status.hasSavepoint()) {
                if (status.isDebug()) {
                    logger.debug("Rolling back transaction to savepoint");
                }
                status.rollbackToHeldSavepoint();
            }
            //如果是新事務(wù),回滾事務(wù)
            else if (status.isNewTransaction()) {
                if (status.isDebug()) {
                    logger.debug("Initiating transaction rollback");
                }
                doRollback(status);
            }
            //如果有事務(wù)但不是新事務(wù),則把標(biāo)記事務(wù)狀態(tài),等事務(wù)鏈執(zhí)行完畢后統(tǒng)一回滾
            else if (status.hasTransaction()) {
                if (status.isLocalRollbackOnly() || isGlobalRollbackOnParticipationFailure()) {
                    if (status.isDebug()) {
                        logger.debug("Participating transaction failed - marking existing transaction as rollback-only");
                    }
                    doSetRollbackOnly(status);
                }
                else {
                    if (status.isDebug()) {
                        logger.debug("Participating transaction failed - letting transaction originator decide on rollback");
                    }
                }
            }
            else {
                logger.debug("Should roll back transaction but cannot - no transaction available");
            }
        }
        catch (RuntimeException ex) {
            triggerAfterCompletion(status, TransactionSynchronization.STATUS_UNKNOWN);
            throw ex;
        }
        catch (Error err) {
            triggerAfterCompletion(status, TransactionSynchronization.STATUS_UNKNOWN);
            throw err;
        }
        triggerAfterCompletion(status, TransactionSynchronization.STATUS_ROLLED_BACK);
    }
    finally {
        //清空記錄的資源并將掛起的資源恢復(fù)
        cleanupAfterCompletion(status);
    }
}

回滾處理的邏輯如下,其實(shí)代碼已經(jīng)很清晰了。

  1. 如果存在安全點(diǎn),則回滾事務(wù)至安全點(diǎn),這個(gè)主要是處理嵌套事務(wù),回滾安全點(diǎn)的操作還是交給了數(shù)據(jù)庫處理.
public void rollbackToHeldSavepoint() throws TransactionException {
    if (!hasSavepoint()) {
        throw new TransactionUsageException(
                "Cannot roll back to savepoint - no savepoint associated with current transaction");
    }
    getSavepointManager().rollbackToSavepoint(getSavepoint());
    getSavepointManager().releaseSavepoint(getSavepoint());
    setSavepoint(null);
}

因?yàn)檫@里使用的是JDBC的方式進(jìn)行數(shù)據(jù)庫連接,所以getSavepointManager返回的是JdbcTransactionObjectSupport,看下JdbcTransactionObjectSupport#rollbackToSavepoint

@Override
public void rollbackToSavepoint(Object savepoint) throws TransactionException {
    ConnectionHolder conHolder = getConnectionHolderForSavepoint();
    try {
        conHolder.getConnection().rollback((Savepoint) savepoint);
    }
    catch (Throwable ex) {
        throw new TransactionSystemException("Could not roll back to JDBC savepoint", ex);
    }
}
  1. 當(dāng)前事務(wù)是一個(gè)新事務(wù)時(shí),那么直接回滾,使用的是DataSourceTransactionManager事務(wù)管理器,所以調(diào)用DataSourceTransactionManager#doRollback,直接調(diào)用數(shù)據(jù)庫連接的回滾方法。
@Override
protected void doRollback(DefaultTransactionStatus status) {
    DataSourceTransactionObject txObject = (DataSourceTransactionObject) status.getTransaction();
    Connection con = txObject.getConnectionHolder().getConnection();
    if (status.isDebug()) {
        logger.debug("Rolling back JDBC transaction on Connection [" + con + "]");
    }
    try {
        con.rollback();
    }
    catch (SQLException ex) {
        throw new TransactionSystemException("Could not roll back JDBC transaction", ex);
    }
}
  1. 當(dāng)前存在事務(wù),但又不是一個(gè)新的事務(wù),只把事務(wù)的狀態(tài)標(biāo)記為read-only,等到事務(wù)鏈執(zhí)行完畢后,統(tǒng)一回滾,調(diào)用DataSourceTransactionManager#doSetRollbackOnly
@Override
protected void doSetRollbackOnly(DefaultTransactionStatus status) {
    DataSourceTransactionObject txObject = (DataSourceTransactionObject) status.getTransaction();
    if (status.isDebug()) {
        logger.debug("Setting JDBC transaction [" + txObject.getConnectionHolder().getConnection() +
                "] rollback-only");
    }
    txObject.setRollbackOnly();
}
  1. 清空記錄的資源并將掛起的資源恢復(fù)
private void cleanupAfterCompletion(DefaultTransactionStatus status) {
    //設(shè)置完成狀態(tài),避免重復(fù)調(diào)用
    status.setCompleted();
    //如果是新的同步狀態(tài),則需要將綁定到當(dāng)前線程的事務(wù)信息清理,傳播行為中掛起事務(wù)的都會(huì)清理
    if (status.isNewSynchronization()) {
        TransactionSynchronizationManager.clear();
    }
    //如果是新事務(wù),清理數(shù)據(jù)庫連接
    if (status.isNewTransaction()) {
        doCleanupAfterCompletion(status.getTransaction());
    }
    //將掛起的事務(wù)恢復(fù)
    if (status.getSuspendedResources() != null) {
        if (status.isDebug()) {
            logger.debug("Resuming suspended transaction after completion of inner transaction");
        }
        resume(status.getTransaction(), (SuspendedResourcesHolder) status.getSuspendedResources());
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,554評論 19 139
  • Spring 事務(wù)屬性分析 事務(wù)管理對于企業(yè)應(yīng)用而言至關(guān)重要。它保證了用戶的每一次操作都是可靠的,即便出現(xiàn)了異常的...
    壹點(diǎn)零閱讀 1,381評論 0 2
  • 這部分的參考文檔涉及數(shù)據(jù)訪問和數(shù)據(jù)訪問層和業(yè)務(wù)或服務(wù)層之間的交互。 Spring的綜合事務(wù)管理支持覆蓋很多細(xì)節(jié),然...
    竹天亮閱讀 1,099評論 0 0
  • 前言 今天是平安夜,先祝大家平安夜快樂。 我們之前的數(shù)十篇文章分析了 Spring 和 Mybatis 的原理,基...
    莫那一魯?shù)?/span>閱讀 14,483評論 3 31
  • 時(shí)間過得飛快,焦急等待手術(shù)的日子仿佛就在昨天,而今天周三,距離上周四手術(shù)日已近一周時(shí)間過去了。老爸恢復(fù)的不錯(cuò),好像...
    吳佟閱讀 256評論 0 0

友情鏈接更多精彩內(nèi)容