Spring源码剖析-Transactional 事务执行流程 傷城~ 2022-10-12 05:48 225阅读 0赞 # 前言 # 上一篇《[Transactional源码解析][Transactional]》我们介绍了Spring对Transactional的解析,也就是事务的初始化工作,这一篇我们接着来分析事务的执行流程。 # 事务拦截器:TransactionInterceptor # `TransactionInterceptor`是事务拦截器,该类实现了`TransactionAspectSupport` , `TransactionAspectSupport` 中持有 `TransactionManager` ,拥有处理事务的能力。同时该类还实现了 `MethodInterceptor` 接口 ,它也作为AOP的拦截器。拦截器链中每个拦截器都有一个invoke方法,该方法就是对某个方法进行事务增强的入口,因此主要看invoke方法的实现逻辑! 源码如下: public class TransactionInterceptor extends TransactionAspectSupport implements MethodInterceptor, Serializable { public TransactionInterceptor() { } //PlatformTransactionManager:事务管理器 public TransactionInterceptor(PlatformTransactionManager ptm, Properties attributes) { setTransactionManager(ptm); setTransactionAttributes(attributes); } //根据事务管理器PlatformTransactionManager,和事务注解源构造一个TransactionInterceptor public TransactionInterceptor(PlatformTransactionManager ptm, TransactionAttributeSource tas) { setTransactionManager(ptm); setTransactionAttributeSource(tas); } //当程序执行事务方法的时候会走invoke ,MethodInvocation:方法调用的描述,在方法调用时提供给拦截器 @Override @Nullable public Object invoke(MethodInvocation invocation) throws Throwable { // 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); // Adapt to TransactionAspectSupport's invokeWithinTransaction... //调用方法,有事务支持 return invokeWithinTransaction(invocation.getMethod(), targetClass, invocation::proceed); } } 该类首先会通过 MethodInvocation(方法调用描述) 得到目标类 ,然后以事务的方式执行方法 invokeWithinTransaction。该方法是其父类的方法 public abstract class TransactionAspectSupport implements BeanFactoryAware, InitializingBean { /** * General delegate for around-advice-based subclasses, delegating to several other template * methods on this class. Able to handle {@link CallbackPreferringPlatformTransactionManager} * as well as regular {@link PlatformTransactionManager} implementations. * @param method the Method being invoked * @param targetClass the target class that we're invoking the method on * @param invocation the callback to use for proceeding with the target invocation * @return the return value of the method, if any * @throws Throwable propagated from the target invocation */ @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. //获取事务属性源:即 @Transactional注解的属性 TransactionAttributeSource tas = getTransactionAttributeSource(); //获取事务属性 final TransactionAttribute txAttr = (tas != null ? tas.getTransactionAttribute(method, targetClass) : null); //事务管理器 final PlatformTransactionManager tm = determineTransactionManager(txAttr); //方法名,类名+方法名:如 cn.xx.UserServiceImpl.save final String joinpointIdentification = methodIdentification(method, targetClass, txAttr); //声明式事务处理 @Transactional if (txAttr == null || !(tm instanceof CallbackPreferringPlatformTransactionManager)) { // 【标记1】Standard transaction demarcation with getTransaction and commit/rollback calls. //创建TransactionInfo,事务详情对象,其中包括事务管理器(transactionManager), //事务属性(transactionAttribute),方法名(joinpointIdentification),事务状态(transactionStatus) TransactionInfo txInfo = createTransactionIfNecessary(tm, txAttr, joinpointIdentification); Object retVal = null; try { // This is an around advice: Invoke the next interceptor in the chain. // This will normally result in a target object being invoked. //【标记2】执行方法,这是一个环绕通知,通常会导致目标对象被调用 retVal = invocation.proceedWithInvocation(); } catch (Throwable ex) { // target invocation exception //回滚事务:AfterThrowing completeTransactionAfterThrowing(txInfo, ex); throw ex; } finally { //清理事务 cleanupTransactionInfo(txInfo); } //AfterReturning:后置通知,提交事务 commitTransactionAfterReturning(txInfo); return retVal; } else { final ThrowableHolder throwableHolder = new ThrowableHolder(); // It's a CallbackPreferringPlatformTransactionManager: pass a TransactionCallback in. try { Object result = ((CallbackPreferringPlatformTransactionManager) tm).execute(txAttr, status -> { TransactionInfo txInfo = prepareTransactionInfo(tm, txAttr, joinpointIdentification, status); try { return invocation.proceedWithInvocation(); } 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); } }); // Check result state: It might indicate a Throwable to rethrow. if (throwableHolder.throwable != null) { throw throwableHolder.throwable; } return result; } 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; } } } 上面方法是事务处理的宏观流程,支持编程时和声明式的事务处理,这里是使用了模板模式,细节交给子类去实现,这里我们总结一下上面方法的流程 * 获取事务属性源TransactionAttributeSource 在上一章节有说道该类 * 加载TransactionManager 事务管理器 * 对声明式或者编程式的事务处理 * 创建 TransactionInfo 事务信息对象,其中包括事务管理器(transactionManager),事务属性(transactionAttribute),方法唯一标识(joinpointIdentification),事务状态(transactionStatus) * 执行目标方法:invocation.proceedWithInvocation * 出现异常,则回滚事务:completeTransactionAfterThrowing,默认是对RuntimeException异常回滚 * 清理事务信息:cleanupTransactionInfo * 提交事务:commitTransactionAfterReturning 下面来分析具体的每个步骤流程 ## 创建事务信息:createTransactionIfNecessary ## createTransactionIfNecessary 是事务流程中的第一个方法,目的是根据给定的 TransactionAttribute 创建一个事务,其中包括事务实例的创建,事务传播行为处理,开启事务等。 protected TransactionInfo createTransactionIfNecessary(@Nullable PlatformTransactionManager tm, @Nullable TransactionAttribute txAttr, final String joinpointIdentification) { //如果未指定名称,则应用方法标识作为事务名称 // If no name specified, apply method identification as transaction name. if (txAttr != null && txAttr.getName() == null) { txAttr = new DelegatingTransactionAttribute(txAttr) { @Override public String getName() { return joinpointIdentification; } }; } TransactionStatus status = null; if (txAttr != null) { if (tm != null) { //根据TransactionAttribute 事务属性创建一个事务状态对象 status = tm.getTransaction(txAttr); } else { if (logger.isDebugEnabled()) { logger.debug("Skipping transactional joinpoint [" + joinpointIdentification + "] because no transaction manager has been configured"); } } } return prepareTransactionInfo(tm, txAttr, joinpointIdentification, status); } ### 获取事务状态:tm.getTransaction ### 见:`AbstractPlatformTransactionManager#getTransaction` @Override public final TransactionStatus getTransaction(@Nullable TransactionDefinition definition) throws TransactionException { //开启一个事务,创建了一个DataSourceTransactionObject对象,其中绑定了ConnectionHolder Object transaction = doGetTransaction(); // Cache debug flag to avoid repeated checks. boolean debugEnabled = logger.isDebugEnabled(); if (definition == null) { // Use defaults if no transaction definition given. definition = new DefaultTransactionDefinition(); } //判断是否已经存在事务,会进行事务传播机制的判断 //判断连接不为空且连接(connectionHolder)中的 transactionActive 不为空 if (isExistingTransaction(transaction)) { //如果存在事务,走这里 // Existing transaction found -> check propagation behavior to find out how to behave. return handleExistingTransaction(definition, transaction, debugEnabled); } //事务超时时间判断 // Check definition settings for new transaction. if (definition.getTimeout() < TransactionDefinition.TIMEOUT_DEFAULT) { throw new InvalidTimeoutException("Invalid transaction timeout", definition.getTimeout()); } //【PROPAGATION_MANDATORY处理】 如果当前事务不存在,PROPAGATION_MANDATORY要求必须已有事务,则抛出异常 // No existing transaction found -> check propagation behavior to find out how to proceed. if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_MANDATORY) { throw new IllegalTransactionStateException( "No existing transaction found for transaction marked with propagation 'mandatory'"); } //【如果没有事务,对于下面三种事务传播行为都需要新开事务】 else if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRED || definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRES_NEW || definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NESTED) { //这三种事务传播机制都需要新开事务,先挂起事务 SuspendedResourcesHolder suspendedResources = suspend(null); if (debugEnabled) { logger.debug("Creating new transaction with name [" + definition.getName() + "]: " + definition); } try { boolean newSynchronization = (getTransactionSynchronization() != SYNCHRONIZATION_NEVER); //创建一个新的TransactionStatus DefaultTransactionStatus status = newTransactionStatus( definition, transaction, true, newSynchronization, debugEnabled, suspendedResources); //开始事务,创建一个DataSourceTransactionObject //设置 ConnectionHolder,设置隔离级别、设置timeout, 切换事务手动提交 //如果是新连接,绑定到当前线程 doBegin(transaction, definition); //针对当期线程的新事务同步设置 prepareSynchronization(status, definition); return status; } catch (RuntimeException | Error ex) { resume(null, suspendedResources); throw ex; } } else { // Create "empty" transaction: no actual transaction, but potentially synchronization. if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT && logger.isWarnEnabled()) { logger.warn("Custom isolation level specified but no actual transaction initiated; " + "isolation level will effectively be ignored: " + definition); } boolean newSynchronization = (getTransactionSynchronization() == SYNCHRONIZATION_ALWAYS); //创建一个newTransactionStatus return prepareTransactionStatus(definition, null, true, newSynchronization, debugEnabled, null); } } 该方法主要做了如下事情: * 开启一个事务 创建了一个DataSourceTransactionObject 事务实例对象,其中绑定了ConnectionHolder,ConnectionHolder底层是ThreadLocal保存了当前线程的数据库连接信息。 * 如果当前线程存在事务,则转向嵌套事务的处理。 * 校验事务超时时间 * 如果事务传播机制是 PROPAGATION\_MANDATORY ,如果不存在事务就抛异常 * 创建一个新的TransactionStatus:DefaultTransactionStatus。 * 完善事务信息设置ConnectionHolder、设置隔离级别、设置timeout,连接绑定到当前线程。 回顾一下事务传播行为: <table> <thead> <tr> <th>事务传播行为类型</th> <th>说明</th> </tr> </thead> <tbody> <tr> <td>PROPAGATION_REQUIRED</td> <td>如果当前没有事务,就新建一个事务,如果已经存在一个事务中,加入到这个事务中。这是最常见的选择。</td> </tr> <tr> <td>PROPAGATION_SUPPORTS</td> <td>支持当前事务,如果当前没有事务,就以非事务方式执行。</td> </tr> <tr> <td>PROPAGATION_MANDATORY</td> <td>使用当前的事务,如果当前没有事务,就抛出异常。</td> </tr> <tr> <td>PROPAGATION_REQUIRES_NEW</td> <td>新建事务,如果当前存在事务,把当前事务挂起。</td> </tr> <tr> <td>PROPAGATION_NOT_SUPPORTED</td> <td>以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。</td> </tr> <tr> <td>PROPAGATION_NEVER</td> <td>以非事务方式执行,如果当前存在事务,则抛出异常。</td> </tr> <tr> <td>PROPAGATION_NESTED</td> <td>如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行与PROPAGATION_REQUIRED类似的操作。</td> </tr> </tbody> </table> ### 处理嵌套事务 :handleExistingTransaction ### //为现有事务创建 TransactionStatus。 private TransactionStatus handleExistingTransaction( TransactionDefinition definition, Object transaction, boolean debugEnabled) throws TransactionException { //以非事务方式执行,如果当前存在事务,则抛出异常。 if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NEVER) { throw new IllegalTransactionStateException( "Existing transaction found for transaction marked with propagation 'never'"); } //以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。并把事务信息设置为null if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NOT_SUPPORTED) { if (debugEnabled) { logger.debug("Suspending current transaction"); } Object suspendedResources = suspend(transaction); boolean newSynchronization = (getTransactionSynchronization() == SYNCHRONIZATION_ALWAYS); return prepareTransactionStatus( definition, null, false, newSynchronization, debugEnabled, suspendedResources); } //新建事务,如果当前存在事务,把当前事务挂起。当然会创建新的连接,让业务在新的事务中完成,之后恢复挂起的事务。 if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRES_NEW) { if (debugEnabled) { logger.debug("Suspending current transaction, creating new transaction with name [" + definition.getName() + "]"); } SuspendedResourcesHolder suspendedResources = suspend(transaction); try { boolean newSynchronization = (getTransactionSynchronization() != SYNCHRONIZATION_NEVER); //新开一个事务 DefaultTransactionStatus status = newTransactionStatus( definition, transaction, true, newSynchronization, debugEnabled, suspendedResources); doBegin(transaction, definition); //初始化事务同步 prepareSynchronization(status, definition); return status; } catch (RuntimeException | Error beginEx) { resumeAfterBeginException(transaction, suspendedResources, beginEx); throw beginEx; } } //如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行与PROPAGATION_REQUIRED类似的操作。 if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NESTED) { //是否运行嵌套事务 if (!isNestedTransactionAllowed()) { throw new NestedTransactionNotSupportedException( "Transaction manager does not allow nested transactions by default - " + "specify 'nestedTransactionAllowed' property with value 'true'"); } if (debugEnabled) { logger.debug("Creating nested transaction with name [" + definition.getName() + "]"); } //对嵌套事务使用保存点 if (useSavepointForNestedTransaction()) { // Create savepoint within existing Spring-managed transaction, // through the SavepointManager API implemented by TransactionStatus. // Usually uses JDBC 3.0 savepoints. Never activates Spring synchronization. //如果是JDBC,使用保存点方式支持事务回滚 DefaultTransactionStatus status = prepareTransactionStatus(definition, transaction, false, false, debugEnabled, null); status.createAndHoldSavepoint(); return status; } else { //如果是类似于JTA这种还无法使用保存点,处理方式如同PROPAGATION_REQUIRES_NEW // Nested transaction through nested begin and commit/rollback calls. // Usually only for JTA: Spring synchronization might get activated here // in case of a pre-existing JTA transaction. boolean newSynchronization = (getTransactionSynchronization() != SYNCHRONIZATION_NEVER); DefaultTransactionStatus status = newTransactionStatus( definition, transaction, true, newSynchronization, debugEnabled, null); doBegin(transaction, definition); prepareSynchronization(status, definition); return status; } } // Assumably PROPAGATION_SUPPORTS or PROPAGATION_REQUIRED. if (debugEnabled) { logger.debug("Participating in existing transaction"); } if (isValidateExistingTransaction()) { if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) { Integer currentIsolationLevel = TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(); if (currentIsolationLevel == null || currentIsolationLevel != definition.getIsolationLevel()) { Constants isoConstants = DefaultTransactionDefinition.constants; throw new IllegalTransactionStateException("Participating transaction with definition [" + definition + "] specifies isolation level which is incompatible with existing transaction: " + (currentIsolationLevel != null ? isoConstants.toCode(currentIsolationLevel, DefaultTransactionDefinition.PREFIX_ISOLATION) : "(unknown)")); } } if (!definition.isReadOnly()) { if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { throw new IllegalTransactionStateException("Participating transaction with definition [" + definition + "] is not marked as read-only but existing transaction is"); } } } boolean newSynchronization = (getTransactionSynchronization() != SYNCHRONIZATION_NEVER); return prepareTransactionStatus(definition, transaction, false, newSynchronization, debugEnabled, null); } ### 新开启事务:DataSourceTransactionManager\#doBegin ### /** * This implementation sets the isolation level but ignores the timeout. */ @Override protected void doBegin(Object transaction, TransactionDefinition definition) { //创建 DataSource 事务对象 DataSourceTransactionObject txObject = (DataSourceTransactionObject) transaction; Connection con = null; try { if (!txObject.hasConnectionHolder() || txObject.getConnectionHolder().isSynchronizedWithTransaction()) { //获取连接 Connection newCon = obtainDataSource().getConnection(); if (logger.isDebugEnabled()) { logger.debug("Acquired Connection [" + newCon + "] for JDBC transaction"); } //把链接设置给DataSourceTransactionObject txObject.setConnectionHolder(new ConnectionHolder(newCon), true); } txObject.getConnectionHolder().setSynchronizedWithTransaction(true); con = txObject.getConnectionHolder().getConnection(); //设置事务隔离级别 ,使用, 以及ReadOnly Integer previousIsolationLevel = DataSourceUtils.prepareConnectionForTransaction(con, definition); txObject.setPreviousIsolationLevel(previousIsolationLevel); // Switch to manual commit if necessary. This is very expensive in some JDBC drivers, // so we don't want to do it unnecessarily (for example if we've explicitly // configured the connection pool to set it already). if (con.getAutoCommit()) { txObject.setMustRestoreAutoCommit(true); if (logger.isDebugEnabled()) { logger.debug("Switching JDBC Connection [" + con + "] to manual commit"); } //设置手动提交,由Spring来控制事务提交 con.setAutoCommit(false); } prepareTransactionalConnection(con, definition); //设置事务Active为true txObject.getConnectionHolder().setTransactionActive(true); //设置事务超时时间 int timeout = determineTimeout(definition); if (timeout != TransactionDefinition.TIMEOUT_DEFAULT) { txObject.getConnectionHolder().setTimeoutInSeconds(timeout); } //把连接绑定到当前线程 // Bind the connection holder to the thread. if (txObject.isNewConnectionHolder()) { TransactionSynchronizationManager.bindResource(obtainDataSource(), txObject.getConnectionHolder()); } } catch (Throwable ex) { if (txObject.isNewConnectionHolder()) { DataSourceUtils.releaseConnection(con, obtainDataSource()); txObject.setConnectionHolder(null, false); } throw new CannotCreateTransactionException("Could not open JDBC Connection for transaction", ex); } } 这个方法是事务开始的方法,因为它已经尝试和数据库进行连接了,然后又做了一些基础设置 * 设置事务的隔离级别,如果DB的隔离级别和事务属性源(TransactionAttribute )即:用户定义的事务隔离级别不一致,使用用户定义的隔离级别 * 把事务自动提交改为false,由Spring来控制事务提交 * 把 TransactionActive 状态设置为true,代表事务是active 激活状态 * 设置事务超时时间 * 把连接绑定到当前对象 到这, createTransactionIfNecessary 方法中的业务就分析完了,接下来就是 调用 `invocation.proceedWithInvocation()` 去执行目标类的方法,如果出现异常,会走catch中的回滚事务代码。 ## 回滚事务:completeTransactionAfterThrowing ## 代码回到`TransactionAspectSupport#invokeWithinTransaction` ,我们跟一下`completeTransactionAfterThrowing(txInfo, ex);` 回滚事务代码,源码如下 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); } //判断异常类型决定是否要回滚 //默认判断异常是否是 RuntimeException 类型或者是 Error 类型 //可以指定异常处理类型,例如:@Transactional(rollbackFor=Exception.class) if (txInfo.transactionAttribute != null && txInfo.transactionAttribute.rollbackOn(ex)) { try { //走事务管理器的rollback回滚事务 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; } } } } 首先是判断了异常的类型符不符合回滚条件,如果符合就调用事务管理器的回滚逻辑,如果不符合回滚条件就走事务管理器的commit提交事务,下面是回滚逻辑:`AbstractPlatformTransactionManager#rollback` @Override public final void rollback(TransactionStatus status) throws TransactionException { 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; //处理回滚 processRollback(defStatus, false); } /** * Process an actual rollback. * The completed flag has already been checked. * @param status object representing the transaction * @throws TransactionException in case of rollback failure */ private void processRollback(DefaultTransactionStatus status, boolean unexpected) { try { boolean unexpectedRollback = unexpected; try { //触发事务同步器TransactionSynchronization中的beforeCompletion回调 //比如调用SqlSessionSynchronization#beforeCompletion 释放资源,sqlSession close等 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"); } //走的是 Connection.rollback回滚 doRollback(status); } else { // Participating in larger transaction // 如果当前事务不是独立的事务,那么只能标记状态,等到事务链执行完毕后统一回滚 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"); } // 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; } // 触发所有 TransactionSynchronization 同步器中对应的 afterCompletion 方法 //比如调用 SqlSessionSynchronization#beforeCompletion 释放资源,重置SqlSession等 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 { //执行清空资源 , 恢复挂起的资源 cleanupAfterCompletion(status); } } 总结一下回滚逻辑 * 触发TransactionSynchronization中的beforeCompletion回调 , TransactionSynchronization定义是事务同步逻辑。比如:SqlSessionSynchronization\#beforeCompletion 就用来释放资源,sqlSession close等 * 如果有保存点,就使用保存点信息进行回滚 * 如果是新开的是事务,使用底层数据库的API回滚 * 其他情况比如JTA模式就标记回滚,等到提交的时候统一回滚 ### 事务清理:cleanupAfterCompletion ### private void cleanupAfterCompletion(DefaultTransactionStatus status) { //设置完成状态 status.setCompleted(); if (status.isNewSynchronization()) { //事务同步管理器清理 TransactionSynchronizationManager.clear(); } if (status.isNewTransaction()) { 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()); } } 1. 如果是新的同步状态,则走`TransactionSynchronizationManager.clear();`清除当前线程的整个事务同步状态 2. 如果是新开的事务,则走`doCleanupAfterCompletion`清理资源,该方法做了如下事情: * 把数据库连接和当前线程解绑 * 重置连接,设置自动提交为true * 如果是新开的事务,就释放连接对象 * 清空ConnectionHolder 1. 如果之前有挂起的事务,就走resume恢复 ## 事务提交:commitTransactionAfterReturning ## protected void commitTransactionAfterReturning(@Nullable TransactionInfo txInfo) { if (txInfo != null && txInfo.getTransactionStatus() != null) { if (logger.isTraceEnabled()) { logger.trace("Completing transaction for [" + txInfo.getJoinpointIdentification() + "]"); } txInfo.getTransactionManager().commit(txInfo.getTransactionStatus()); } } @Override public final void commit(TransactionStatus status) throws TransactionException { 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; //如果事务被标记回滚,直接回滚 if (defStatus.isLocalRollbackOnly()) { if (defStatus.isDebug()) { logger.debug("Transactional code has requested rollback"); } //走回滚流程 processRollback(defStatus, false); return; } if (!shouldCommitOnGlobalRollbackOnly() && defStatus.isGlobalRollbackOnly()) { if (defStatus.isDebug()) { logger.debug("Global transaction is marked as rollback-only but transactional code requested commit"); } processRollback(defStatus, true); return; } //执行提交流程 processCommit(defStatus); } 提交事务之前会先判断是否要回滚,然后触发回滚,否则就正常走提交事务流程 private void processCommit(DefaultTransactionStatus status) throws TransactionException { try { boolean beforeCompletionInvoked = false; try { boolean unexpectedRollback = false; prepareForCommit(status); //调用 同步器的beforeCommit :比如走 SqlSessionSynchronization#beforeCommit执行 SqlSession().commit() 提交事务 triggerBeforeCommit(status); //触发同步器的beforeCompletion,比如走:SqlSessionSynchronization#beforeCompletion 解绑资源,执行sqlSession.close triggerBeforeCompletion(status); beforeCompletionInvoked = true; //如果有保存点 if (status.hasSavepoint()) { if (status.isDebug()) { logger.debug("Releasing transaction savepoint"); } unexpectedRollback = status.isGlobalRollbackOnly(); //释放保存点 status.releaseHeldSavepoint(); } //如果是新开事务 else if (status.isNewTransaction()) { if (status.isDebug()) { logger.debug("Initiating transaction commit"); } unexpectedRollback = status.isGlobalRollbackOnly(); //调用collection.commit 提交事务 doCommit(status); } else if (isFailEarlyOnGlobalRollbackOnly()) { unexpectedRollback = status.isGlobalRollbackOnly(); } // Throw UnexpectedRollbackException if we have a global rollback-only // marker but still didn't get a corresponding exception from commit. if (unexpectedRollback) { throw new UnexpectedRollbackException( "Transaction silently rolled back because it has been marked as rollback-only"); } } catch (UnexpectedRollbackException ex) { // can only be caused by doCommit triggerAfterCompletion(status, TransactionSynchronization.STATUS_ROLLED_BACK); throw ex; } catch (TransactionException ex) { // can only be caused by doCommit if (isRollbackOnCommitFailure()) { doRollbackOnCommitException(status, ex); } else { triggerAfterCompletion(status, TransactionSynchronization.STATUS_UNKNOWN); } throw ex; } catch (RuntimeException | Error ex) { if (!beforeCompletionInvoked) { triggerBeforeCompletion(status); } doRollbackOnCommitException(status, ex); throw ex; } // Trigger afterCommit callbacks, with an exception thrown there // propagated to callers but the transaction still considered as committed. try { //触发 afterCommit 回调 triggerAfterCommit(status); } finally { // 释放资源:this.holder.getSqlSession().close(); triggerAfterCompletion(status, TransactionSynchronization.STATUS_COMMITTED); } } finally { cleanupAfterCompletion(status); } } 1. 当事务有保存点不会去提交事务,而是释放保存点 2. 如果是新开的事务就调用collection.comit 提交事务 3. 然后就是各种释放资源,关闭SqlSession等操作 # 总结 # 就分析到这里吧,总体来说,当Spring启动就会为标记了@Transcational的方法生成代理,然后代理对象在执行方法的时候会通过TransactionInterceptor来执行事务增强,而事务的业务主要是调用TransactionManager 来完成。 深夜码字,实在太困了,还是早点休息吧明天还上班,喜欢的话给个好评,你的鼓励是我最大的动力,谢谢!!! [Transactional]: https://blog.csdn.net/u014494148/article/details/118398677
还没有评论,来说两句吧...