Spring事務信息準備好后谴仙,如果我們的程序出現(xiàn)了異常,又會如何回滾事務呢碾盐?這節(jié)我們分析Spring事務回滾原理晃跺。
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è)務邏輯
retVal = invocation.proceedWithInvocation();
}
catch (Throwable ex) {
// target invocation exception
completeTransactionAfterThrowing(txInfo, ex);
throw ex;
}
當執(zhí)行業(yè)務邏輯拋出異常后,調(diào)用completeTransactionAfterThrowing方法回滾事務毫玖,這里得注意的是掀虎,如果程序不把異常拋出,而且捕獲異常付枫,Spring是不會回滾的烹玉。
protected void completeTransactionAfterThrowing(TransactionInfo txInfo, Throwable ex) {
//判斷是否存在事務
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.
//如果不滿足符合的異常類型,也同樣會提交
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;
}
}
}
}
回滾邏輯如下:
- 判斷是否存在事務叶眉,只有存在事務才執(zhí)行回滾
- 根據(jù)異常類型判斷是否回滾址儒。如果異常類型不符合,仍然會提交事務
- 回滾處理
詳細分析每個步驟
回滾條件
txInfo.transactionAttribute.rollbackOn(ex)
TransactionInfo中的TransactionAttribute屬性值的是RuleBasedTransactionAttribute衅疙,在解析@Transactional注解時初始化莲趣,它的rollbackOn方法實現(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沒有配置喧伞,默認調(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沒有配置,則默認使用RuntimeException和Error異常状植。
回滾處理
txInfo.getTransactionManager().rollback(txInfo.getTransactionStatus());
交給事務管理器回滾事務浊竟。
private void processRollback(DefaultTransactionStatus status) {
try {
try {
triggerBeforeCompletion(status);
//如果有安全點,回滾至安全點
if (status.hasSavepoint()) {
if (status.isDebug()) {
logger.debug("Rolling back transaction to savepoint");
}
status.rollbackToHeldSavepoint();
}
//如果是新事務津畸,回滾事務
else if (status.isNewTransaction()) {
if (status.isDebug()) {
logger.debug("Initiating transaction rollback");
}
doRollback(status);
}
//如果有事務但不是新事務振定,則把標記事務狀態(tài),等事務鏈執(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 {
//清空記錄的資源并將掛起的資源恢復
cleanupAfterCompletion(status);
}
}
回滾處理的邏輯如下肉拓,其實代碼已經(jīng)很清晰了后频。
- 如果存在安全點,則回滾事務至安全點暖途,這個主要是處理嵌套事務卑惜,回滾安全點的操作還是交給了數(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);
}
因為這里使用的是JDBC的方式進行數(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);
}
}
- 當前事務是一個新事務時残揉,那么直接回滾,使用的是DataSourceTransactionManager事務管理器芋浮,所以調(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);
}
}
- 當前存在事務,但又不是一個新的事務纸巷,只把事務的狀態(tài)標記為read-only镇草,等到事務鏈執(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();
}
- 清空記錄的資源并將掛起的資源恢復
private void cleanupAfterCompletion(DefaultTransactionStatus status) {
//設置完成狀態(tài)瘤旨,避免重復調(diào)用
status.setCompleted();
//如果是新的同步狀態(tài)梯啤,則需要將綁定到當前線程的事務信息清理琅摩,傳播行為中掛起事務的都會清理
if (status.isNewSynchronization()) {
TransactionSynchronizationManager.clear();
}
//如果是新事務而线,清理數(shù)據(jù)庫連接
if (status.isNewTransaction()) {
doCleanupAfterCompletion(status.getTransaction());
}
//將掛起的事務恢復
if (status.getSuspendedResources() != null) {
if (status.isDebug()) {
logger.debug("Resuming suspended transaction after completion of inner transaction");
}
resume(status.getTransaction(), (SuspendedResourcesHolder) status.getSuspendedResources());
}
}