6、Spring事务 commit和rollback

2019-10-23  本文已影响0人  timar

这里主要关注事务的执行过程。根据之前的分析已经知道切面逻辑在TransactionInterceptor中。


image.png

TransactionInterceptor实现了通知Advice,BeanFactoryAware,生成bean后会调用其setBeanFactory方法,InitializingBean,会调用afterPropertiesSet。

TransactionAspectSupport中封装了具体的事务逻辑包括事务创建、提交、回滚,执行入口在MethodInterceptor的invoke方法中

org.springframework.transaction.interceptor.TransactionInterceptor#invoke

@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);
}
 
 
@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.
    // 返回AnnotationTransactionAttributeSource  
   TransactionAttributeSource tas = getTransactionAttributeSource();
    // 从方法或者类上获取@Transactionl注解属性
   final TransactionAttribute txAttr = (tas != null ? tas.getTransactionAttribute(method, targetClass) : null);
    // 从容器中获取class为PlatformTransactionManager的事务管理器,实际获取到的是DataSourceTransactionManager
   final PlatformTransactionManager tm = determineTransactionManager(txAttr);
    // 为jointpoint生成一个标识符,具体是包名+类名+方法名
   final String joinpointIdentification = methodIdentification(method, targetClass, txAttr);
 
   if (txAttr == null || !(tm instanceof CallbackPreferringPlatformTransactionManager)) {
      // Standard transaction demarcation with getTransaction and commit/rollback calls.
        // 创建事务
      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.
        // 这里就是调用service中的执行逻辑,如userMapper.insert(user);
         retVal = invocation.proceedWithInvocation();
      }
      catch (Throwable ex) {
         // target invocation exception
        // 发生异常,事务回滚
         completeTransactionAfterThrowing(txInfo, ex);
         throw ex;
      }
      finally {
        // 不论成功或失败,都会执行,作用是当有两层事物时,如A调用B,B事务执行完后,设置当前事务为oldTransactionInfo,也就是A的事务。
        // 正向操作也就是设置A事务为oldTransactionInfo在方法prepareTransactionInfo中
        // 即使事务传播级别是REQUIRED/NESTED/REQUIRED_NEW,都会生成一个新的TransactionInfocleanupTransactionInfo(txInfo);      }
        // 没有发生异常,事务提交
      commitTransactionAfterReturning(txInfo);
      return retVal;
   }
    // 忽略...
    
}
 
// 是否需要创建事务
protected TransactionInfo createTransactionIfNecessary(@Nullable PlatformTransactionManager tm,
      @Nullable TransactionAttribute txAttr, final String joinpointIdentification) {
 
    // DelegatingTransactionAttribute对AnnotationTransactionAttributeSource作了一层封装,没有其他作用,赋予了一个名字
   // 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) {
        // 通过事务管理器来开启事务
         status = tm.getTransaction(txAttr);
      }
      else {
         if (logger.isDebugEnabled()) {
            logger.debug("Skipping transactional joinpoint [" + joinpointIdentification +
                  "] because no transaction manager has been configured");
         }
      }
   }
    // 根据事务管理器,事务属性,标识符,事务状态构造一个TransactionInfo,并将TransactionInfo和当前线程绑定,并保存旧的事务信息TransactionInfo
   return prepareTransactionInfo(tm, txAttr, joinpointIdentification, status);
}

TransactionSynchronizationManager事务同步管理器,其中有几个ThreadLocal属性,存储当前事务的一些属性
resources:类型是map,主要保存了DefaultSqlSessionFactory和SqlSessionHoler,HikariDataSource和ConnectionHolder的映射关系。ConnectionHolder封装了实际数据库连接,SqlSessionHoler封装了DefaultSqlSession
synchronizations:一些TransactionSynchronization的集合,实际保存的是实现类SqlSessionSynchronization,SqlSessionSynchronization包含了事务提交前、事务完成前、事务回滚前的一些操作和事务的暂挂和解暂挂
currentTransactionName:当前线程事务的名字
currentTransactionReadOnly:当前线程事务是否是只读,true或false
currentTransactionIsolationLevel:当前线程事务的隔离级别
actualTransactionActive:当前线程是否有事务处于active状态

// 通过事务管理器来获取事务
// org.springframework.transaction.support.AbstractPlatformTransactionManager#getTransaction
public final TransactionStatus getTransaction(@Nullable TransactionDefinition definition) throws TransactionException {
    // 创建一个新的DataSourceTransactionObject,并从TransactionSynchronizationManager中获取当前事务的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();
   }
 
    // 当前线程是否已经存在事务,判断条件是从TransactionSynchronizationManager中获取的ConnectionHolder不为空,并且ConnectionHolder的transactionActive属性为true
   if (isExistingTransaction(transaction)) {
      // Existing transaction found -> check propagation behavior to find out how to behave.
        // 当前已经存在一个事务的处理逻辑
      return handleExistingTransaction(definition, transaction, debugEnabled);
   }
 
    // 以下都是当前不存在事务的情况
    // 检查配置的超时时间是否比-1还小
   // Check definition settings for new transaction.
   if (definition.getTimeout() < TransactionDefinition.TIMEOUT_DEFAULT) {
      throw new InvalidTimeoutException("Invalid transaction timeout", definition.getTimeout());
   }
     
    // 如果事务的传播级别配置的是TransactionDefinition.PROPAGATION_MANDATORY,直接报错,因为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'");
   }
    // 如果事务传播级别配置的是REQUIRED、REQUIRES_NEW、NESTED,创建一个新的事务
   else if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRED ||
         definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRES_NEW ||
         definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NESTED) {
        // suspend方法是用来暂挂事务的,这里因为当前不存在事务,所以这里实际不会有任何操作
      SuspendedResourcesHolder suspendedResources = suspend(null);
      if (debugEnabled) {
         logger.debug("Creating new transaction with name [" + definition.getName() + "]: " + definition);
      }
      try {
        // getTransactionSynchronization()返回的是变量transactionSynchronization,暂时不太明白这个变量有什么用处
         boolean newSynchronization = (getTransactionSynchronization() != SYNCHRONIZATION_NEVER);
        // 创建一个新的DefaultTransactionStatus
         DefaultTransactionStatus status = newTransactionStatus(
               definition, transaction, true, newSynchronization, debugEnabled, suspendedResources);
        // 开启事务逻辑,实现在DataSourceTransactionManager中
         doBegin(transaction, definition);
        // 设置当前事务的一些属性到TransactionSynchronizationManager中
         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);
      return prepareTransactionStatus(definition, null, true, newSynchronization, debugEnabled, null);
   }
}

由于后面TransactionSynchronization会多次提到,所以这里先看一下TransactionSynchronization的实现类SqlSessionSynchronization

private static final class SqlSessionSynchronization extends TransactionSynchronizationAdapter {
 
  private final SqlSessionHolder holder;
 
  private final SqlSessionFactory sessionFactory;
 
  private boolean holderActive = true;
 
  public SqlSessionSynchronization(SqlSessionHolder holder, SqlSessionFactory sessionFactory) {
    notNull(holder, "Parameter 'holder' must be not null");
    notNull(sessionFactory, "Parameter 'sessionFactory' must be not null");
 
    this.holder = holder;
    this.sessionFactory = sessionFactory;
  }
 
 
  @Override
  public int getOrder() {
    // order right before any Connection synchronization
    return DataSourceUtils.CONNECTION_SYNCHRONIZATION_ORDER - 1;
  }
 
    // 暂挂,解除defaultSqlSessionFactory、ConnectionHolder和当前线程的绑定
  @Override
  public void suspend() {
    if (this.holderActive) {
      if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Transaction synchronization suspending SqlSession [" + this.holder.getSqlSession() + "]");
      }
      TransactionSynchronizationManager.unbindResource(this.sessionFactory);
    }
  }
 
    // 解暂挂,将defaultSqlSessionFactory、ConnectionHolder和当前线程绑定
  @Override
  public void resume() {
    if (this.holderActive) {
      if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Transaction synchronization resuming SqlSession [" + this.holder.getSqlSession() + "]");
      }
      TransactionSynchronizationManager.bindResource(this.sessionFactory, this.holder);
    }
  }
 
    // 事务提前前调用
  @Override
  public void beforeCommit(boolean readOnly) {
    // Connection commit or rollback will be handled by ConnectionSynchronization or
    // DataSourceTransactionManager.
    // But, do cleanup the SqlSession / Executor, including flushing BATCH statements so
    // they are actually executed.
    // SpringManagedTransaction will no-op the commit over the jdbc connection
    // TODO This updates 2nd level caches but the tx may be rolledback later on!
    // 当前有事务处于激活状态
    if (TransactionSynchronizationManager.isActualTransactionActive()) {
      try {
        if (LOGGER.isDebugEnabled()) {
          LOGGER.debug("Transaction synchronization committing SqlSession [" + this.holder.getSqlSession() + "]");
        }
        // 调用defaultSqlSession的commit
        this.holder.getSqlSession().commit();
      } catch (PersistenceException p) {
        if (this.holder.getPersistenceExceptionTranslator() != null) {
          DataAccessException translated = this.holder
              .getPersistenceExceptionTranslator()
              .translateExceptionIfPossible(p);
          if (translated != null) {
            throw translated;
          }
        }
        throw p;
      }
    }
  }
 
    // 事务提交前,beforeCommit调用后调用
  @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()) {
      if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Transaction synchronization deregistering SqlSession [" + this.holder.getSqlSession() + "]");
      }
      // 解除defaultSqlSessionFactory、ConnectionHolder和当前线程的绑定
      TransactionSynchronizationManager.unbindResource(sessionFactory);
      this.holderActive = false;
      if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Transaction synchronization closing SqlSession [" + this.holder.getSqlSession() + "]");
      }
      this.holder.getSqlSession().close();
    }
  }
 
    // 事务提交后调用
  @Override
  public void afterCompletion(int status) {
    if (this.holderActive) {
      // afterCompletion may have been called from a different thread
      // so avoid failing if there is nothing in this one
      if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Transaction synchronization deregistering SqlSession [" + this.holder.getSqlSession() + "]");
      }
      TransactionSynchronizationManager.unbindResourceIfPossible(sessionFactory);
      this.holderActive = false;
      if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Transaction synchronization closing SqlSession [" + this.holder.getSqlSession() + "]");
      }
      this.holder.getSqlSession().close();
    }
    this.holder.reset();
  }
}

看下事务开启的逻辑,主要是从数据源中获取连接,并将连接和线程绑定

// org.springframework.jdbc.datasource.DataSourceTransactionManager#doBegin
protected void doBegin(Object transaction, TransactionDefinition definition) {
   DataSourceTransactionObject txObject = (DataSourceTransactionObject) transaction;
   Connection con = null;
 
   try {
        // 当前事务还没有数据库连接,或者创建了ConnectionHolder但是没有获取数据库物理连接(ConnectionImpl)
      if (!txObject.hasConnectionHolder() ||
            txObject.getConnectionHolder().isSynchronizedWithTransaction()) {
        // 从数据源中获取连接,HikariDataSource
         Connection newCon = obtainDataSource().getConnection();
         if (logger.isDebugEnabled()) {
            logger.debug("Acquired Connection [" + newCon + "] for JDBC transaction");
         }
         txObject.setConnectionHolder(new ConnectionHolder(newCon), true);
      }
 
      txObject.getConnectionHolder().setSynchronizedWithTransaction(true);
        // 实际的数据库连接
      con = txObject.getConnectionHolder().getConnection();
 
        // 设置数据库连接的只读属性和隔离级别属性
      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");
         }
        // 切换autoCommit属性为false
         con.setAutoCommit(false);
      }
 
        // 如果配置的是readOnly=true,则先执行一条SQL,SET TRANSACTION READ ONLY
      prepareTransactionalConnection(con, definition);
      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);
   }
}

后续就是mybatis拿着数据连接进行数据库操作的逻辑了。
下面看下事务的提交与回滚
事务的提交在
org.springframework.transaction.interceptor.TransactionAspectSupport#commitTransactionAfterReturning

// org.springframework.transaction.interceptor.TransactionAspectSupport#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());
   }
}
 
 
// org.springframework.transaction.support.AbstractPlatformTransactionManager#commit
@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;
   }
    // 当有多层事务,如A调用B,没有创建新事务,B发生异常,即使catch住B,A的事务也会回滚。
    // 因为ConnectionHolder的rollbackOnly属性被设置成true,defStatus.isGlobalRollbackOnly()会返回true
   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);
        // 调用TransactionSynchronizationManager中保存的TransactionSynchronization的beforeCommit方法
         triggerBeforeCommit(status);
        // 调用TransactionSynchronizationManager中保存的TransactionSynchronization的beforeCompletion方法
         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();
            // 事务提交逻辑,ConnectionImpl.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 {
        // 调用TransactionSynchronizationManager中保存的TransactionSynchronization的AfterCommit方法
         triggerAfterCommit(status);
      }
      finally {
         triggerAfterCompletion(status, TransactionSynchronization.STATUS_COMMITTED);
      }
 
   }
   finally {
        // 设置DefaultTransactionStatus的状态为已完成
        // 从TransactionSynchronizationManager中清除当前线程事务的属性
        // 如果有暂挂事务,则恢复暂挂事务
      cleanupAfterCompletion(status);
   }
}

事务的回滚

private void processRollback(DefaultTransactionStatus status, boolean unexpected) {
   try {
      boolean unexpectedRollback = unexpected;
 
      try {
         triggerBeforeCompletion(status);
 
        // 如果有savepoint,回滚到保存点,如事务隔离级别为NESTED时
         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);
         }
         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");
                  }
                    // 最终结果是调用DataSourceTransactionManager的setRollbackOnly方法,将ConnectionHolder的属性rollbackOnly设置为true
                    // 即使本层异常catch住,在父事务(A调用B,A的事务),A事务也会执行rollback
                  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;
      }
 
      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);
   }
}

嵌套事务的处理
// org.springframework.transaction.support.AbstractPlatformTransactionManager#handleExistingTransaction

private TransactionStatus handleExistingTransaction(
      TransactionDefinition definition, Object transaction, boolean debugEnabled)
      throws TransactionException {
 
    // TransactionDefinition.PROPAGATION_NEVER,不支持事务,如果当前有事务,则报异常
   if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NEVER) {
      throw new IllegalTransactionStateException(
            "Existing transaction found for transaction marked with propagation 'never'");
   }
 
    // PROPAGATION_NOT_SUPPORTED,如果当前已经存在事务,暂挂已有事务
   if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NOT_SUPPORTED) {
      if (debugEnabled) {
         logger.debug("Suspending current transaction");
      }
        // 将当前事务挂起,以无事务状态往下执行
        // 暂挂的操作实际就是保存当前事务的一些状态到对象SuspendedResourcesHolder中
      Object suspendedResources = suspend(transaction);
      boolean newSynchronization = (getTransactionSynchronization() == SYNCHRONIZATION_ALWAYS);
      return prepareTransactionStatus(
            definition, null, false, newSynchronization, debugEnabled, suspendedResources);
   }
 
    // PROPAGATION_REQUIRES_NEW,当前已有事务,仍然会创建一个新的事务
   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_NESTED,不改变当前事务的属性,创建一个savepoint,创建savepoint的过程实际上是执行了一条SQL,savepoint 'savepoint_name'
    // save point的作用是回滚时,可以回滚到保存点
   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.
         DefaultTransactionStatus status =
               prepareTransactionStatus(definition, transaction, false, false, debugEnabled, null);
         status.createAndHoldSavepoint();
         return status;
      }
      else {
         // 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);
}

事务的暂挂和解暂挂

// org.springframework.transaction.support.AbstractPlatformTransactionManager#suspend
protected final SuspendedResourcesHolder suspend(@Nullable Object transaction) throws TransactionException {
    // 暂挂的前提是当前线程已经有事务是处于激活状态的
   if (TransactionSynchronizationManager.isSynchronizationActive()) {
        //
      List<TransactionSynchronization> suspendedSynchronizations = doSuspendSynchronization();
      try {
         Object suspendedResources = null;
         if (transaction != null) {
            suspendedResources = doSuspend(transaction);
         }
            // 获取当前事务的一些属性
         String name = TransactionSynchronizationManager.getCurrentTransactionName();
         TransactionSynchronizationManager.setCurrentTransactionName(null);
         boolean readOnly = TransactionSynchronizationManager.isCurrentTransactionReadOnly();
         TransactionSynchronizationManager.setCurrentTransactionReadOnly(false);
         Integer isolationLevel = TransactionSynchronizationManager.getCurrentTransactionIsolationLevel();
         TransactionSynchronizationManager.setCurrentTransactionIsolationLevel(null);
         boolean wasActive = TransactionSynchronizationManager.isActualTransactionActive();
         TransactionSynchronizationManager.setActualTransactionActive(false);
         return new SuspendedResourcesHolder(
               suspendedResources, suspendedSynchronizations, name, readOnly, isolationLevel, wasActive);
      }
      catch (RuntimeException | Error ex) {
         // doSuspend failed - original transaction is still active...
         doResumeSynchronization(suspendedSynchronizations);
         throw ex;
      }
   }
   else if (transaction != null) {
      // Transaction active but no synchronization active.
      Object suspendedResources = doSuspend(transaction);
      return new SuspendedResourcesHolder(suspendedResources);
   }
   else {
      // Neither transaction nor synchronization active.
      return null;
   }
}
 
 
// 获取TransactionSynchronizationManager中保存的事务同步器,循环调用suspend()方法
private List<TransactionSynchronization> doSuspendSynchronization() {
   List<TransactionSynchronization> suspendedSynchronizations =
         TransactionSynchronizationManager.getSynchronizations();
   for (TransactionSynchronization synchronization : suspendedSynchronizations) {
      synchronization.suspend();
   }
   TransactionSynchronizationManager.clearSynchronization();
   return suspendedSynchronizations;
}

解暂挂在事务提交之后org.springframework.transaction.support.AbstractPlatformTransactionManager#cleanupAfterCompletion

private void cleanupAfterCompletion(DefaultTransactionStatus status) {
   status.setCompleted();
   if (status.isNewSynchronization()) {
        // 清除TransactionSynchronizationManager中当前线程的属性
      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());
   }
}

有如下demo,AService调用BService,BService设置的事务传播级别为REQUIRED

@Transactional(rollbackFor = Exception.class)
@Override
public int insert(User user, Book book){
    int insert = userMapper.insert(user);
    try {
        BService.addBook(book);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return insert;
}
事务传播级别 当前有事物 当前无事务 B发生异常 B无异常
REQUIRED 继承 new 回滚 均正常提交
SUPPORTS 继承 无事务方式执行 回滚 均正常提交(由A一起提交事务)
MANDATORY 继承 异常 回滚 均正常提交
REQUIRES_NEW new new 提交 均正常提交
NOT_SUPPORTED 暂挂 无事务方式执行 提交 均正常提交(由A一起提交事务)
NEVER 异常 无事务方式执行
NESTED 嵌套 new 回滚到保存点,A正常提交 均正常提交
上一篇下一篇

猜你喜欢

热点阅读