@Transactional原理分析

@Transactional原理分析

1、spring事务简单使用

下面是注解方式使用spring事务的简单示例。

1、Spring 支持多种事务管理方式,而使用注解方式进行事务管理需要引入如下依赖:

<!-- Spring JDBC -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>${spring.version}</version>
</dependency>

spring-jdbc依赖中引入了spring-tx依赖,Spring事务的实际源码在spring-tx中,所以只需要引入spring-jdbc就可以使用spring事务了。

2、通过spring配置文件开启和管理事务。

    <!-- 开启事务支持 -->
    <tx:annotation-driven/>
    
    <!-- 事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- 配置数据源-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
    ...省略...
    </bean>

在spring项目中,可以通过<tx:annotation-driven/>标签开启事务,在springboot项目中,可以通过@EnableTransactionManagement注解(用在启动类上)开启事务。

3、在需要使用事务的类或方法上使用@Transactional注解。

@Service
public class UserService ...{

	//事务注解
	@Transactional
	public void insert(User user){
		...
	}

}

Spring事务的实际源码在spring-tx中。在Spring项目中,由于spring-jdbc依赖中引入了spring-tx依赖,所以只需引入spring-jdbc就可以使用spring事务了。在springboot项目中,由于spring-boot-starter-jdbc依赖中引入了spring-jdbc依赖,spring-jdbc依赖中引入了spring-tx依赖,所以只需引入spring-boot-starter-jdbc就可以使用spring事务了。

对于springboot项目,如果引入spring-boot-starter-jdbc依赖,无论在类或方法上是否有@Transactional注解,在获取所有的增强器时,都会从spring容器中获取到事务对应的增强器BeanFactoryTransactionAttributeSourceAdvisor。

如果springboot项目中使用mybatis,只需引入mybatis-spring-boot-starter依赖也可以使用事务,因为mybatis-spring-boot-starter依赖中引入了spring-boot-starter-jdbc依赖。

@Transactional是spring中声明式事务管理的注解配置方式,@Transactional注解可以进行开启事务、提交或者回滚事务的操作,通过AOP的方式进行管理,底层是通过AOP实现的。通过@Transactional注解就能让spring为我们管理事务,免去了重复的事务管理逻辑,减少对业务代码的侵入,使开发人员能够专注于业务层面开发。

由于@Transactional注解是通过AOP实现的,可以猜想:在服务启动时,创建spring容器,进行一系列相关bean的创建,如果开启了AOP功能(对于基于注解实现的AOP,可以在启动类上加上@EnableAspectJAutoProxy注解来开启AOP功能),还会缓存所有的切面信息,如果引入与jdbc相关的依赖(spring-boot-starter-jdbc),与@Transactional相关的切面信息自然也会被放到缓存中。如果在一个类的public方法上使用@Transactional注解,在创建该类的bean实例时,会创建该类的代理对象,spring容器中保存的是该类的代理对象。底层源码会通过TransactionInterceptor拦截器对使用@Transactional注解的方法进行增强,该拦截器实现了org.aopalliance.intercept.MethodInterceptor接口。

2、TransactionInterceptor源码分析

如果引入了spring-tx事务依赖,由AOP的原理可知(Spring AOP的原理(上)),在获取所有的增强器时,就会根据internalTransactionAdvisor这个beanName从spring容器中获取对应的增强器BeanFactoryTransactionAttributeSourceAdvisor。

在获取适配当前bean的增强器时,会判断目标方法或类上是否有事务注解,如果当前bean的类和方法上都没有事务注解,则BeanFactoryTransactionAttributeSourceAdvisor增强器与当前bean无法匹配,说明当前bean不需要进行事务操作。

若当前bean的类或方法上有@Transactional事务注解,在创建代理对象之后,调用目标方法时,会将BeanFactoryTransactionAttributeSourceAdvisor增强器转成TransactionInterceptor拦截器,实际是从BeanFactoryTransactionAttributeSourceAdvisor中获取TransactionInterceptor,如下图所示。

TransactionInterceptor是事务拦截器,该类实现了TransactionAspectSupport , TransactionAspectSupport 中持有 TransactionManager,拥有处理事务的能力。同时该类还实现了 MethodInterceptor 接口 ,它也作为AOP的拦截器。拦截器链中每个拦截器都有一个invoke方法(可以参考:Spring AOP的原理(下)),该方法就是对某个方法进行事务增强的入口,因此主要看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,该方法是其父类TransactionAspectSupport的方法。

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)) {
			// Standard transaction demarcation with getTransaction and commit/rollback calls.
			//1.创建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
				//3.回滚事务:AfterThrowing
				completeTransactionAfterThrowing(txInfo, ex);
				throw ex;
			}
			finally {
				//4.清理事务
				cleanupTransactionInfo(txInfo);
			}
			//5.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;
			}
		}
	}

}

上面方法是事务处理的宏观流程,支持编程式和声明式的事务处理,这里是使用了模板模式,细节交给子类去实现,这里我们总结一下上面方法的流程:

1、获取事务属性源TransactionAttributeSource

2、加载TransactionManager 事务管理器

3、对声明式或者编程式的事务处理

4、创建 TransactionInfo 事务信息对象,其中包括事务管理器(transactionManager),事务属性(transactionAttribute),方法唯一标识(joinpointIdentification),事务状态(transactionStatus)

5、执行目标方法:invocation.proceedWithInvocation

6、若出现异常,则回滚事务:completeTransactionAfterThrowing,默认是对RuntimeException异常回滚

7、清理事务信息:cleanupTransactionInfo

8、提交事务:commitTransactionAfterReturning

下面对其中几个主要步骤进行分析。

2.1、创建事务信息

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);
	}

2.1.1、获取事务状态

调用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);
		}
	}

该方法主要做了如下事情:

1.开启一个事务,创建了一个DataSourceTransactionObject 事务实例对象,其中绑定了ConnectionHolder,ConnectionHolder底层是ThreadLocal保存了当前线程的数据库连接信息。

2.如果当前线程存在事务,则转向嵌套事务的处理。

3.校验事务超时时间

4.如果事务不存在,则开启新事物

5.创建一个新的TransactionStatus:DefaultTransactionStatus。

6.完善事务信息设置ConnectionHolder、设置隔离级别、设置timeout,连接绑定到当前线程。

回顾一下事务传播行为:

2.1.2、处理嵌套事务

    //为现有事务创建 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);
	}

2.1.3、新开启事务

调用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);
		}
	}

这个方法是事务开始的方法,因为它已经尝试和数据库进行连接了,然后又做了一些基础设置:

1.设置事务的隔离级别,如果DB的隔离级别和事务属性源(TransactionAttribute )即:用户定义的事务隔离级别不一致,使用用户定义的隔离级别。

2.把事务自动提交改为false,由Spring来控制事务提交。

3.把 TransactionActive 状态设置为true,代表事务是active 激活状态。

4.设置事务超时时间。

5.把连接绑定到当前对象。

到此, createTransactionIfNecessary 方法中的业务就分析完了,接下来就是 调用 invocation.proceedWithInvocation() 去执行目标类的方法,如果出现异常,会走catch中的回滚事务代码。

2.2、回滚事务

代码回到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);
		}
	}

总结一下回滚逻辑:

1.触发TransactionSynchronization中的beforeCompletion回调 , TransactionSynchronization定义是事务同步逻辑。比如:SqlSessionSynchronization#beforeCompletion 就用来释放资源,sqlSession close等。

2.如果有保存点,就使用保存点信息进行回滚。

3.如果是新开的事务,使用底层数据库的API回滚。

4.其他情况比如JTA模式就标记回滚,等到提交的时候统一回滚。

2.3、清理事务

    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());
		}
	}

如果是新的同步状态,则走TransactionSynchronizationManager.clear();清除当前线程的整个事务同步状态。

如果是新开的事务,则走doCleanupAfterCompletion清理资源,该方法做了如下事情:

1.把数据库连接和当前线程解绑

2.重置连接,设置自动提交为true

3.如果是新开的事务,就释放连接对象

4.清空ConnectionHolder

5.如果之前有挂起的事务,就走resume恢复

2.4、提交事务

    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);
		}
	}

当事务有保存点不会去提交事务,而是释放保存点。如果是新开的事务就调用collection.comit 提交事务。然后就是各种释放资源,关闭SqlSession等操作。

总结:

当Spring启动就会为标记了@Transcational的方法生成代理,然后代理对象在执行方法的时候会通过TransactionInterceptor来执行事务增强,而事务的业务主要是调用TransactionManager 来完成。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值