Spring 随笔 transactional 5-事务回滚

1. 从TransactionInterceptor着手

	// public class TransactionInterceptor extends TransactionAspectSupport implements MethodInterceptor
	// org.springframework.transaction.interceptor.TransactionInterceptor#invoke
	@Override
	@Nullable
	public Object invoke(MethodInvocation invocation) throws Throwable {
		// 获取被代理的类
		// 因为TransactionAttribute是间接的跟targetClass绑定的
		// Work out the target class: may be {@code null}.
		// The TransactionAttributeSource should be passed the target class
		// as well as the method, which may be from an interface.
		Class<?> targetClass = (invocation.getThis() != null ? AopUtils.getTargetClass(invocation.getThis()) : null);

		// step into ...
		// Adapt to TransactionAspectSupport's invokeWithinTransaction...
		return invokeWithinTransaction(invocation.getMethod(), targetClass, invocation::proceed);
	}

	// org.springframework.transaction.interceptor.TransactionAspectSupport#invokeWithinTransaction
	@Nullable
	protected Object invokeWithinTransaction(Method method, @Nullable Class<?> targetClass,
			final InvocationCallback invocation) throws Throwable {

		// If the transaction attribute is null, the method is non-transactional.
		TransactionAttributeSource tas = getTransactionAttributeSource();
		final TransactionAttribute txAttr = (tas != null ? tas.getTransactionAttribute(method, targetClass) : null);
		final TransactionManager tm = determineTransactionManager(txAttr);

		if (this.reactiveAdapterRegistry != null && tm instanceof ReactiveTransactionManager) {
			ReactiveTransactionSupport txSupport = this.transactionSupportCache.computeIfAbsent(method, key -> {
				if (KotlinDetector.isKotlinType(method.getDeclaringClass()) && KotlinDelegate.isSuspend(method)) {
					throw new TransactionUsageException(
							"Unsupported annotated transaction on suspending function detected: " + method +
							". Use TransactionalOperator.transactional extensions instead.");
				}
				ReactiveAdapter adapter = this.reactiveAdapterRegistry.getAdapter(method.getReturnType());
				if (adapter == null) {
					throw new IllegalStateException("Cannot apply reactive transaction to non-reactive return type: " +
							method.getReturnType());
				}
				return new ReactiveTransactionSupport(adapter);
			});
			return txSupport.invokeWithinTransaction(
					method, targetClass, invocation, txAttr, (ReactiveTransactionManager) tm);
		}

		PlatformTransactionManager ptm = asPlatformTransactionManager(tm);
		final String joinpointIdentification = methodIdentification(method, targetClass, txAttr);

		if (txAttr == null || !(ptm instanceof CallbackPreferringPlatformTransactionManager)) {
			// Standard transaction demarcation with getTransaction and commit/rollback calls.
			TransactionInfo txInfo = createTransactionIfNecessary(ptm, txAttr, joinpointIdentification);

			Object retVal;
			try {
				// 执行入参中的回调函数,即参与到拦截器链的演进逻辑中
				// This is an around advice: Invoke the next interceptor in the chain.
				// This will normally result in a target object being invoked.
				retVal = invocation.proceedWithInvocation();
			}
			catch (Throwable ex) {
				// step into ...
				// target invocation exception
				completeTransactionAfterThrowing(txInfo, ex);
				throw ex;
			}
			finally {
				// step into ..
				// 把当前线程绑定的事务改成之前的事务(比如:将子事务切换到父事务)
				cleanupTransactionInfo(txInfo);
			}

			if (retVal != null && vavrPresent && VavrDelegate.isVavrTry(retVal)) {
				// Set rollback-only in case of Vavr failure matching our rollback rules...
				TransactionStatus status = txInfo.getTransactionStatus();
				if (status != null && txAttr != null) {
					retVal = VavrDelegate.evaluateTryFailure(retVal, txAttr, status);
				}
			}

			// step into ...
			commitTransactionAfterReturning(txInfo);
			return retVal;
		}

		else {
			Object result;
			final ThrowableHolder throwableHolder = new ThrowableHolder();

			// It's a CallbackPreferringPlatformTransactionManager: pass a TransactionCallback in.
			try {
				result = ((CallbackPreferringPlatformTransactionManager) ptm).execute(txAttr, status -> {
					TransactionInfo txInfo = prepareTransactionInfo(ptm, txAttr, joinpointIdentification, status);
					try {
						Object retVal = invocation.proceedWithInvocation();
						if (retVal != null && vavrPresent && VavrDelegate.isVavrTry(retVal)) {
							// Set rollback-only in case of Vavr failure matching our rollback rules...
							retVal = VavrDelegate.evaluateTryFailure(retVal, txAttr, status);
						}
						return retVal;
					}
					catch (Throwable ex) {
						if (txAttr.rollbackOn(ex)) {
							// A RuntimeException: will lead to a rollback.
							if (ex instanceof RuntimeException) {
								throw (RuntimeException) ex;
							}
							else {
								throw new ThrowableHolderException(ex);
							}
						}
						else {
							// A normal return value: will lead to a commit.
							throwableHolder.throwable = ex;
							return null;
						}
					}
					finally {
						cleanupTransactionInfo(txInfo);
					}
				});
			}
			catch (ThrowableHolderException ex) {
				throw ex.getCause();
			}
			catch (TransactionSystemException ex2) {
				if (throwableHolder.throwable != null) {
					logger.error("Application exception overridden by commit exception", throwableHolder.throwable);
					ex2.initApplicationException(throwableHolder.throwable);
				}
				throw ex2;
			}
			catch (Throwable ex2) {
				if (throwableHolder.throwable != null) {
					logger.error("Application exception overridden by commit exception", throwableHolder.throwable);
				}
				throw ex2;
			}

			// Check result state: It might indicate a Throwable to rethrow.
			if (throwableHolder.throwable != null) {
				throw throwableHolder.throwable;
			}
			return result;
		}
	}

2. completeTransactionAfterThrowing:回滚

	// org.springframework.transaction.interceptor.TransactionAspectSupport#completeTransactionAfterThrowing
	protected void completeTransactionAfterThrowing(@Nullable TransactionInfo txInfo, Throwable ex) {
		if (txInfo != null && txInfo.getTransactionStatus() != null) {
			if (logger.isTraceEnabled()) {
				logger.trace("Completing transaction for [" + txInfo.getJoinpointIdentification() +
						"] after exception: " + ex);
			}
			// step into ...
			// 回滚还是直接提交
			if (txInfo.transactionAttribute != null && txInfo.transactionAttribute.rollbackOn(ex)) {
				try {
					// step into ...
					txInfo.getTransactionManager().rollback(txInfo.getTransactionStatus());
				}
				catch (TransactionSystemException ex2) {
					logger.error("Application exception overridden by rollback exception", ex);
					ex2.initApplicationException(ex);
					throw ex2;
				}
				catch (RuntimeException | Error ex2) {
					logger.error("Application exception overridden by rollback exception", ex);
					throw ex2;
				}
			}
			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 | Error ex2) {
					logger.error("Application exception overridden by commit exception", ex);
					throw ex2;
				}
			}
		}
	}

2.1 DelegatingTransactionAttribute.rollbackOn:当前事务是否需要回滚

	// org.springframework.transaction.interceptor.DelegatingTransactionAttribute#rollbackOn
	@Override
	public boolean rollbackOn(Throwable ex) {
		// step into ...
		return this.targetAttribute.rollbackOn(ex);
	}
	
	// org.springframework.transaction.interceptor.RuleBasedTransactionAttribute#rollbackOn
	@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;

		// 默认为空
		//比如指定rollBackFor=SQLException.class,就会走这里
		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.
		if (winner == null) {
			logger.trace("No relevant rollback rule found: applying default rules");
			// step into ...
			return super.rollbackOn(ex);
		}

		return !(winner instanceof NoRollbackRuleAttribute);
	}
	
	// org.springframework.transaction.interceptor.DefaultTransactionAttribute#rollbackOn
	@Override
	public boolean rollbackOn(Throwable ex) {
		// step out ...
		// 这就是默认的RollbackFor
		return (ex instanceof RuntimeException || ex instanceof Error);
	}

2.2 AbstractPlatformTransactionManager.rollback:事务管理器回滚操作

	// org.springframework.transaction.support.AbstractPlatformTransactionManager#rollback
	@Override
	public final void rollback(TransactionStatus status) throws TransactionException {
		// org.springframework.transaction.support.AbstractTransactionStatus#completed
		if (status.isCompleted()) {
			throw new IllegalTransactionStateException(
					"Transaction is already completed - do not call commit or rollback more than once per transaction");
		}

		DefaultTransactionStatus defStatus = (DefaultTransactionStatus) status;
		// Step into ...
		processRollback(defStatus, false);
	}
	
	// org.springframework.transaction.support.AbstractPlatformTransactionManager#processRollback
	private void processRollback(DefaultTransactionStatus status, boolean unexpected) {
		try {
		
			// 不期待回滚的标志位
			boolean unexpectedRollback = unexpected;

			try {
				// Step into ...
				triggerBeforeCompletion(status);

				// 具备有保存点
				// NESTED走这里
				// ((this.transaction instanceof SmartTransactionObject) &&
				// ((SmartTransactionObject) this.transaction).isRollbackOnly());
				if (status.hasSavepoint()) {
					if (status.isDebug()) {
						logger.debug("Rolling back transaction to savepoint");
					}
					// step into ...
					status.rollbackToHeldSavepoint();
				}
				// 新建的事务(最外层的顶层事务)
				else if (status.isNewTransaction()) {
					if (status.isDebug()) {
						logger.debug("Initiating transaction rollback");
					}
					// step into ...
					doRollback(status);
				}
				else {
					// 作为嵌套的一个子事务参与到外层事务中
					// Participating in larger transaction
					if (status.hasTransaction()) {
						// 检查回滚标识 org.springframework.transaction.support.AbstractTransactionStatus#rollbackOnly
						// 或者有全局的回滚标识
						if (status.isLocalRollbackOnly() || isGlobalRollbackOnParticipationFailure()) {
							if (status.isDebug()) {
								logger.debug("Participating transaction failed - marking existing transaction as rollback-only");
							}
							// step into ...
							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");
					}
					
					// 当需要提前失败(不等待外层事务,子事务先异常就先回滚)时,异常回滚才有意义
					// 直接检查 org.springframework.transaction.support.AbstractPlatformTransactionManager#failEarlyOnGlobalRollbackOnly
					// Unexpected rollback only matters here if we're asked to fail early
					if (!isFailEarlyOnGlobalRollbackOnly()) {
						unexpectedRollback = false;
					}
				}
			}
			catch (RuntimeException | Error ex) {
				triggerAfterCompletion(status, TransactionSynchronization.STATUS_UNKNOWN);
				throw ex;
			}

			// step into ...
			triggerAfterCompletion(status, TransactionSynchronization.STATUS_ROLLED_BACK);

			// 还记得有那么一次...反正事务用多了,这个报错信息就不需要多说了
			// Raise UnexpectedRollbackException if we had a global rollback-only marker
			if (unexpectedRollback) {
				throw new UnexpectedRollbackException(
						"Transaction rolled back because it has been marked as rollback-only");
			}
		}
		finally {
			// step into ...
			cleanupAfterCompletion(status);
		}
	}

2.2.1 AbstractPlatformTransactionManager.triggerBeforeCompletion:事务管理器完成(提交、回滚)之前回调

	// org.springframework.transaction.support.AbstractPlatformTransactionManager#triggerBeforeCompletion
	protected final void triggerBeforeCompletion(DefaultTransactionStatus status) {
		// org.springframework.transaction.support.DefaultTransactionStatus#newSynchronization
		// true:当前事务需要创建一个新的同步(当前线程的事务与jdbc连接)
		// 如果是嵌套的子事务的话,就不需要了
		if (status.isNewSynchronization()) {
			if (status.isDebug()) {
				logger.trace("Triggering beforeCompletion synchronization");
			}
			// step into ...
			TransactionSynchronizationUtils.triggerBeforeCompletion();
		}
	}
	
	// org.springframework.transaction.support.TransactionSynchronizationUtils#triggerBeforeCompletion
	public static void triggerBeforeCompletion() {
		// 从线程的threadLocal中获取绑定到线程的TransactionSynchronization(当前线程的事务回调方法)
		for (TransactionSynchronization synchronization : TransactionSynchronizationManager.getSynchronizations()) {
			try {
				// step into ...
				synchronization.beforeCompletion();
			}
			catch (Throwable tsex) {
				logger.error("TransactionSynchronization.beforeCompletion threw exception", tsex);
			}
		}
	}
	
	// org.mybatis.spring.SqlSessionUtils.SqlSessionSynchronization#beforeCompletion
	@Override
    public void beforeCompletion() {
      // Issue #18 Close SqlSession and deregister it now
      // because afterCompletion may be called from a different thread
      if (!this.holder.isOpen()) {
        LOGGER
            .debug(() -> "Transaction synchronization deregistering SqlSession [" + this.holder.getSqlSession() + "]");
		// 解绑当前线程的连接,从threadLocal中除名
        TransactionSynchronizationManager.unbindResource(sessionFactory);
		// 取消TransactionSynchronization的连接活跃标志位
        this.holderActive = false;
        LOGGER.debug(() -> "Transaction synchronization closing SqlSession [" + this.holder.getSqlSession() + "]");
		// 释放这个连接
        this.holder.getSqlSession().close();
      }
    }

2.2.2 AbstractTransactionStatus.rollbackToHeldSavepoint:事务回滚至保存点(这里用于嵌套事务)

	// org.springframework.transaction.support.AbstractTransactionStatus#rollbackToHeldSavepoint
	public void rollbackToHeldSavepoint() throws TransactionException {
		Object savepoint = getSavepoint();
		if (savepoint == null) {
			throw new TransactionUsageException(
					"Cannot roll back to savepoint - no savepoint associated with current transaction");
		}
		// step into ...
		getSavepointManager().rollbackToSavepoint(savepoint);
		getSavepointManager().releaseSavepoint(savepoint);
		setSavepoint(null);
	}
	
	// org.springframework.jdbc.datasource.JdbcTransactionObjectSupport#rollbackToSavepoint
	@Override
	public void rollbackToSavepoint(Object savepoint) throws TransactionException {
		ConnectionHolder conHolder = getConnectionHolderForSavepoint();
		try {
			conHolder.getConnection().rollback((Savepoint) savepoint);
			// this.rollbackOnly = false;
			conHolder.resetRollbackOnly();
		}
		catch (Throwable ex) {
			throw new TransactionSystemException("Could not roll back to JDBC savepoint", ex);
		}
		// step out ...
	}

2.2.3 DataSourceTransactionManager.doRollback:回滚最终反应到Connect上

	// org.springframework.jdbc.datasource.DataSourceTransactionManager#doRollback
	@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 {
			// step into ...
			con.rollback();
		}
		catch (SQLException ex) {
			throw new TransactionSystemException("Could not roll back JDBC transaction", ex);
		}
	}
	
	
	// com.zaxxer.hikari.pool.ProxyConnection#rollback()
	// 这里是spring默认的连接池的实现
	// 还有可能是druid啥的
	@Override
   public void rollback() throws SQLException
   {
      delegate.rollback();
      isCommitStateDirty = false;
      lastAccess = currentTime();
	  // step out ...
   }

2.2.4 DataSourceTransactionManager.doSetRollbackOnly:设置事务的回滚标志位(这里回滚子事务)

	// org.springframework.jdbc.datasource.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");
		}
		// step into ...
		txObject.setRollbackOnly();
	}
	
	// org.springframework.jdbc.datasource.DataSourceTransactionManager.DataSourceTransactionObject#setRollbackOnly
	public void setRollbackOnly() {
		// step into ...
		getConnectionHolder().setRollbackOnly();
	}
	
	// org.springframework.transaction.support.ResourceHolderSupport#setRollbackOnly
	public void setRollbackOnly() {
		// step out ...
		// 眼熟的来了
		this.rollbackOnly = true;
	}

2.2.5 AbstractPlatformTransactionManager.triggerAfterCompletion:事务完成钩子(跟前面一样是Synchronization的回调)

	// org.springframework.transaction.support.AbstractPlatformTransactionManager#triggerAfterCompletion
	private void triggerAfterCompletion(DefaultTransactionStatus status, int completionStatus) {
		// 看得出来:跟triggerBeforeCompletion()是对好兄弟了
		// 同理,子事务是不需要走这里的
		if (status.isNewSynchronization()) {
			// Set<TransactionSynchronization> synchs = synchronizations.get();
			List<TransactionSynchronization> synchronizations = TransactionSynchronizationManager.getSynchronizations();
			
			// step into ...
			TransactionSynchronizationManager.clearSynchronization();
			if (!status.hasTransaction() || status.isNewTransaction()) {
				if (status.isDebug()) {
					logger.trace("Triggering afterCompletion synchronization");
				}
				
				// step into ...
				// No transaction or new transaction for the current scope ->
				// invoke the afterCompletion callbacks immediately
				invokeAfterCompletion(synchronizations, completionStatus);
			}
			else if (!synchronizations.isEmpty()) {
				// Existing transaction that we participate in, controlled outside
				// of the scope of this Spring transaction manager -> try to register
				// an afterCompletion callback with the existing (JTA) transaction.
				registerAfterCompletionWithExistingTransaction(status.getTransaction(), synchronizations);
			}
		}
	}
	
	// org.springframework.transaction.support.TransactionSynchronizationManager#clearSynchronization
	public static void clearSynchronization() throws IllegalStateException {
		// synchronizations.get() != null
		if (!isSynchronizationActive()) {
			throw new IllegalStateException("Cannot deactivate transaction synchronization - not active");
		}
		logger.trace("Clearing transaction synchronization");
		synchronizations.remove();
		// step out ...
	}
	
	// org.springframework.transaction.support.AbstractPlatformTransactionManager#invokeAfterCompletion
	protected final void invokeAfterCompletion(List<TransactionSynchronization> synchronizations, int completionStatus) {
		// step into ...
		TransactionSynchronizationUtils.invokeAfterCompletion(synchronizations, completionStatus);
	}
	
	// org.springframework.transaction.support.TransactionSynchronizationUtils#invokeAfterCompletion
	public static void invokeAfterCompletion(@Nullable List<TransactionSynchronization> synchronizations,
			int completionStatus) {

		if (synchronizations != null) {
			for (TransactionSynchronization synchronization : synchronizations) {
				try {
					// step into ...
					synchronization.afterCompletion(completionStatus);
				}
				catch (Throwable tsex) {
					logger.error("TransactionSynchronization.afterCompletion threw exception", tsex);
				}
			}
		}
	}
	
	// org.mybatis.spring.SqlSessionUtils.SqlSessionSynchronization#afterCompletion
	// mybatis的源码缩进真有意思
	@Override
    public void afterCompletion(int status) {
	  // triggerBeforeCompletion()里面已经提前置false了
      if (this.holderActive) {
        // afterCompletion may have been called from a different thread
        // so avoid failing if there is nothing in this one
        LOGGER
            .debug(() -> "Transaction synchronization deregistering SqlSession [" + this.holder.getSqlSession() + "]");
        TransactionSynchronizationManager.unbindResourceIfPossible(sessionFactory);
        this.holderActive = false;
        LOGGER.debug(() -> "Transaction synchronization closing SqlSession [" + this.holder.getSqlSession() + "]");
        this.holder.getSqlSession().close();
      }
      this.holder.reset();
	  // step out ...
    }
  }
  
	// org.springframework.transaction.support.ResourceHolderSupport#reset
	@Override
	public void reset() {
		// step into ...
		clear();
		this.referenceCount = 0;
	}
	
	// org.springframework.transaction.support.ResourceHolderSupport#clear
	public void clear() {
		this.synchronizedWithTransaction = false;
		this.rollbackOnly = false;
		this.deadline = null;
		// step out ...
	}

2.2.6 AbstractPlatformTransactionManager.cleanupAfterCompletion:清理并切换绑定到线程的事务资源

	// org.springframework.transaction.support.AbstractPlatformTransactionManager#cleanupAfterCompletion
	private void cleanupAfterCompletion(DefaultTransactionStatus status) {
		// 将事务完成的标识置true而已
		// org.springframework.transaction.support.AbstractTransactionStatus#completed
		status.setCompleted();
		if (status.isNewSynchronization()) {
			// 这里面不是一坨的threadlocal,给都调用了一遍remove()
			TransactionSynchronizationManager.clear();
		}
		if (status.isNewTransaction()) {
			// 这里也很简单:把DataSourceTransactionObject中的ConnectHolder以及相关变量给置null,释放掉
			doCleanupAfterCompletion(status.getTransaction());
		}
		// 存在挂起的资源就会走这里
		if (status.getSuspendedResources() != null) {
			if (status.isDebug()) {
				logger.debug("Resuming suspended transaction after completion of inner transaction");
			}
			Object transaction = (status.hasTransaction() ? status.getTransaction() : null);
			resume(transaction, (SuspendedResourcesHolder) status.getSuspendedResources());
		}
		// step out ...
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

肯尼思布赖恩埃德蒙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值