深入Spring事务源码剖析事务之事务增强器
这里感谢 CSDN 的原博客: https://blog.csdn.net/qq_41737716/article/details/84860614
1、前情概要
上一篇文章我们说到深入Spring事务源码剖析事务(一),讲解了事务的Advisor是如何注册进Spring容器的,也讲解了Spring是如何将有配置事务的类配置上事务的,实际上也就是用了AOP那一套,也讲解了Advisor,pointcut验证流程,至此,事务的初始化工作都已经完成了,在之后的调用过程,如果代理类的方法被调用,都会调用BeanFactoryTransactionAttributeSourceAdvisor
这个Advisor的增强方法,也就是我们还未提到的那个Advisor里面的advise,还记得吗,在自定义标签的时候我们将TransactionInterceptor
这个Advice作为bean注册进IOC容器,并且将其注入进Advisor中,最终事务的功能都在advise中体现,所以我们先来关注一下TransactionInterceptor
这个类吧。
2、事务增强器TransactionInterceptor
2.1、类继承关系
先来看看此类的继承关系,这个类实现了MethodInterceptor
接口,同时也是一个Advice
,在AOP中,我们知道代理类在执行方法的时候,会动态匹配执行的方法是否有相应的Advisor与之匹配,如果可以匹配,将会把Advisor转换成一个执行链,这个方法在DefaultAdvisorChainFactory
中:
/**
* 从提供的配置实例config中获取advisor列表,遍历处理这些advisor.如果是IntroductionAdvisor,
* 则判断此Advisor能否应用到目标类targetClass上.如果是PointcutAdvisor,则判断
* 此Advisor能否应用到目标方法method上.将满足条件的Advisor通过AdvisorAdaptor转化成Interceptor列表返回.
*/
@Override
public List<Object> getInterceptorsAndDynamicInterceptionAdvice(
Advised config, Method method, @Nullable Class<?> targetClass) {
// This is somewhat tricky... We have to process introductions first,
// but we need to preserve order in the ultimate list.
List<Object> interceptorList = new ArrayList<>(config.getAdvisors().length);
Class<?> actualClass = (targetClass != null ? targetClass : method.getDeclaringClass());
// 查看是否包含IntroductionAdvisor
boolean hasIntroductions = hasMatchingIntroductions(config, actualClass);
// 这里实际上注册一系列AdvisorAdapter,用于将Advisor转化成MethodInterceptor
AdvisorAdapterRegistry registry = GlobalAdvisorAdapterRegistry.getInstance();
for (Advisor advisor : config.getAdvisors()) {
if (advisor instanceof PointcutAdvisor) {
// Add it conditionally.
PointcutAdvisor pointcutAdvisor = (PointcutAdvisor) advisor;
if (config.isPreFiltered() || pointcutAdvisor.getPointcut().getClassFilter().matches(actualClass)) {
// 这个地方这两个方法的位置可以互换下
// 将Advisor转化成Interceptor
// 在这里就是刚才所说的执行链,都将会是MethodInterceptor类型
MethodInterceptor[] interceptors = registry.getInterceptors(advisor);
//检查当前advisor的pointcut是否可以匹配当前方法
MethodMatcher mm = pointcutAdvisor.getPointcut().getMethodMatcher();
// 以下代码略....
}
得到这个执行链之后呢,会去执行MthodInterceptor
的invoke方法(其中一段流程略过,如知道AOP原理将很好理解为什么会执行到invoke方法,本篇文章着重讲解事务功能,对AOP方面调用不多赘述):
@Override
@Nullable
public Object invoke(final 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);
}
2.2、核心事务底层封装实现方法
重点来了,进入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);
// 从属性中获取事务管理器,这里承接上一篇文章中自定义标签那里,在配置文件中配置一个事务管理器
// PlatformTransactionManager有很多种,这里分析常用的DataSourceTransactionManager
final PlatformTransactionManager tm = determineTransactionManager(txAttr);
// 给pointcut一个名称
final String joinpointIdentification = methodIdentification(method, targetClass, txAttr);
if (txAttr == null || !(tm instanceof CallbackPreferringPlatformTransactionManager)) {
// 这里执行声明式事务
// Standard transaction demarcation with getTransaction and commit/rollback calls.
// 创建一个带有事务信息的对象TransactionInfo
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.
// 执行原方法
retVal = invocation.proceedWithInvocation();
}
catch (Throwable ex) {
// target invocation exception
// 如果有异常就走这里,对异常进行处理
completeTransactionAfterThrowing(txInfo, ex);
throw ex;
}
finally {
// 如果Info里存在旧的Info,将旧的Info放入当前线程表示将当前Info变为上一个Info
cleanupTransactionInfo(txInfo);
}
// 如果程序没有发生异常,就会走到这里,执行提交的操作
commitTransactionAfterReturning(txInfo);
return retVal;
}
else {
// 这里执行编程式事务 本文只讨论声明式事务
// 略....
}
}
我们这里先不看Info是如何创建出来的,先来分析一下异常是如何处理,而提交又是怎么处理,然后再回过头去看createTransactionIfNecessary这个方法,相信会更好理解创建Info时的一些行为。
首先先声明一下一些对象,
TransactionInfo
是存放事务信息的对象,这个对象里面有一个属性status
,这个对象描述了事务的状态,是一个新的事务还是一个旧的事务,事务是否有保存点等信息都将存放在这里。后面在将创建一个事务的过程会一一介绍,这里简单介绍一下,在接下来处理异常或是正常事务的处理都会需要用到status对象中的信息进行判断如何操作,所以这里先简单知道一下,在后面重点提到的时候会有恍然大悟的效果。
2.3、处理事务异常的情况
先看看completeTransactionAfterThrowing,当发生异常如何处理:
/**
* Handle a throwable, completing the transaction.
* We may commit or roll back, depending on the configuration.
* @param txInfo information about the current transaction
* @param ex throwable encountered
*/
// 处理异常情况的事务
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
// 如果是Exception这里不会回滚的,除非设置了rollbackFor->Exception
if (txInfo.transactionAttribute != null && txInfo.transactionAttribute.rollbackOn(ex)) {
// 如果该异常需要回滚,则回滚,这里会将Info中的status传入方法
try {
txInfo.getTransactionManager().rollback(txInfo.getTransactionStatus());
}
catch (TransactionSystemException ex2) {
// 略...
}
}
else {
// We don't roll back on this exception.
// Will still roll back if TransactionStatus.isRollbackOnly() is true.
// 如果进入这里,说明此异常不需要进行回滚,会照常提交!这里会将Info中status传入方法
try {
txInfo.getTransactionManager().commit(txInfo.getTransactionStatus());
}
catch (TransactionSystemException ex2) {
// 略...
}
}
}
}
进入txInfo.getTransactionManager().rollback(txInfo.getTransactionStatus()); 看看:
/**
1. This implementation of rollback handles participating in existing
2. transactions. Delegates to {@code doRollback} and
3. {@code doSetRollbackOnly}.
4. @see #doRollback
5. @see #doSetRollbackOnly
*/
@Override
public final void rollback(TransactionStatus status) throws TransactionException {
// 如果status已经被标记完成了,这里抛异常。标记的时机在下面的小结会提到
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);
}
private void processRollback(DefaultTransactionStatus status, boolean unexpected) {
try {
boolean unexpectedRollback = unexpected;
try {
triggerBeforeCompletion(status);
// 如果status有savePoint,说明此事务是NESTD,且为子事务,只回滚到savePoint
if (status.hasSavepoint()) {
if (status.isDebug()) {
logger.debug("Rolling back transaction to savepoint");
}
status.rollbackToHeldSavepoint();
}
// 如果此时的status显示是新的事务才进行回滚
else if (status.isNewTransaction()) {
if (status.isDebug()) {
logger.debug("Initiating transaction rollback");
}
doRollback(status);
}
else {
// Participating in larger transaction
// 如果status中有事务,进入下面
if (status.hasTransaction()) {
if (status.isLocalRollbackOnly() || isGlobalRollbackOnParticipationFailure()) {
if (status.isDebug()) {
logger.debug("Participating transaction failed - marking existing transaction as rollback-only");
}
// 对status中的transaction作一个回滚了的标记
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 {
// 最后完善status
cleanupAfterCompletion(status);
}
}
2.3.1、回顾Status几个关键点!
status.hasSavepoint()
如果status中有savePoint,只回滚到savePoint!status.isNewTransaction()
如果status是一个新事务,才会真正去回滚!status.hasTransaction()
如果status有事务,将会对staus中的事务标记!
那么怎么标记呢?
@Override
protected void doSetRollbackOnly(DefaultTransactionStatus status) {
// 将status中的transaction取出
DataSourceTransactionObject txObject = (DataSourceTransactionObject) status.getTransaction();
if (status.isDebug()) {
logger.debug("Setting JDBC transaction [" + txObject.getConnectionHolder().getConnection() +
"] rollback-only");
}
// transaction执行标记回滚
txObject.setRollbackOnly();
}
public void setRollbackOnly() {
// 这里将transaction里面的connHolder标记回滚
getConnectionHolder().setRollbackOnly();
}
/**
* Mark the resource transaction as rollback-only.
*/
public void setRollbackOnly() {
// 将holder中的这个属性设置成true
this.rollbackOnly = true;
}
这里先懵逼一下,后面讲到提交的处理时就知道这个标记有什么用了。
2.3.2、总结事务异常情况
只有是新的事务才会回滚,或者是NESTED中子事务回滚到SavePoint,这里是否是新的事务将在下面创建事务说明清楚。
2.4、处理事务无异常准备提交的情况
这里回到流程中去,看看commitTransactionAfterReturning(txInfo)
方法做了什么:
/**
* Execute after successful completion of call, but not after an exception was handled.
* Do nothing if we didn't create a transaction.
* @param txInfo information about the current transaction
*/
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());
}
}
/**
* This implementation of commit handles participating in existing
* transactions and programmatic rollback requests.
* Delegates to {@code isRollbackOnly}, {@code doCommit}
* and {@code rollback}.
* @see org.springframework.transaction.TransactionStatus#isRollbackOnly()
* @see #doCommit
* @see #rollback
*/
@Override
public final void commit(TransactionStatus status) throws TransactionException {
// 如果status已经被标记完成了,这里抛异常。标记的时机在下面的小结会提到
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;
}
// defStatus.isGlobalRollbackOnly()这个方法将判断status是否被标记回滚了
// 主要依据是transaction中的connHolder是否被标记,也就是上面提到的标记回滚的情况
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);
}
/**
* Process an actual commit.
* Rollback-only flags have already been checked and applied.
* @param status object representing the transaction
* @throws TransactionException in case of commit failure
*/
private void processCommit(DefaultTransactionStatus status) throws TransactionException {
try {
boolean beforeCompletionInvoked = false;
try {
boolean unexpectedRollback = false;
prepareForCommit(status);
triggerBeforeCommit(status);
triggerBeforeCompletion(status);
beforeCompletionInvoked = true;
// 判断是否有savePoint
if (status.hasSavepoint()) {
if (status.isDebug()) {
logger.debug("Releasing transaction savepoint");
}
unexpectedRollback = status.isGlobalRollbackOnly();
// 不提交,仅仅是释放savePoint
status.releaseHeldSavepoint();
}
// 判断是否是新事务
else if (status.isNewTransaction()) {
if (status.isDebug()) {
logger.debug("Initiating transaction commit");
}
unexpectedRollback = status.isGlobalRollbackOnly();
// 这里才真正去提交!
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) {
// 略...
}
// Trigger afterCommit callbacks, with an exception thrown there
// propagated to callers but the transaction still considered as committed.
try {
triggerAfterCommit(status);
}
finally {
triggerAfterCompletion(status, TransactionSynchronization.STATUS_COMMITTED);
}
}
finally {
// 最后完善清理status
cleanupAfterCompletion(status);
}
}
2.4.1、回顾Status几个关键点!
status.hasSavepoint()
如果status有savePoint,说明此时的事务是嵌套事务NESTED,这个事务外面还有事务,这里不提交,只是释放保存点。这里也可以看出来NESTED的传播行为了。status.isNewTransaction()
如果是新的事务,才会提交!!
2.4.2、总结事务无异常准备提交情况
无论是异常还是无异常,都有对staus进行判断的关键点,需牢记几个status关键点,后面将会恍然大悟!
2.5、小结
这里status是新事务,才会进行提交或回滚,需要读者记好这个状态–>是否是新事务。
而无论是在异常还是没有异常的流程中,最后的finally块中都会执行一个方法cleanupAfterCompletion(status)
/**
* Clean up after completion, clearing synchronization if necessary,
* and invoking doCleanupAfterCompletion.
* @param status object representing the transaction
* @see #doCleanupAfterCompletion
*/
private void cleanupAfterCompletion(DefaultTransactionStatus status) {
// 这里可以看到,在异常或无异常提交最后,都会设置一个完成标记
// 在异常或无异常提交之前都会验证status是否被标记完成
// 由此得出结论,一个status对象只能进入一次commit或者一次rollback
status.setCompleted();
if (status.isNewSynchronization()) {
TransactionSynchronizationManager.clear();
}
// 如果是新事务,这里又提到新事务!!
if (status.isNewTransaction()) {
// 对status中的transaction对象做完善工作
doCleanupAfterCompletion(status.getTransaction());
}
// 如果status中有挂起的对象,进入if语句块
if (status.getSuspendedResources() != null) {
if (status.isDebug()) {
logger.debug("Resuming suspended transaction after completion of inner transaction");
}
// 获取transaction对象
Object transaction = (status.hasTransaction() ? status.getTransaction() : null);
// 恢复transaction
resume(transaction, (SuspendedResourcesHolder) status.getSuspendedResources());
}
}
2.5.1、doCleanupAfterCompletion的完善工作做了什么?
@Override
protected void doCleanupAfterCompletion(Object transaction) {
DataSourceTransactionObject txObject = (DataSourceTransactionObject) transaction;
// Remove the connection holder from the thread, if exposed.
// 如果transaction中的holder是新的话,从当前线程中解绑holder
if (txObject.isNewConnectionHolder()) {
TransactionSynchronizationManager.unbindResource(obtainDataSource());
}
// Reset connection.
// 从transaction中获取holder中的connection
Connection con = txObject.getConnectionHolder().getConnection();
// 将连接重置
try {
if (txObject.isMustRestoreAutoCommit()) {
con.setAutoCommit(true);
}
DataSourceUtils.resetConnectionAfterTransaction(con, txObject.getPreviousIsolationLevel());
}
catch (Throwable ex) {
logger.debug("Could not reset JDBC Connection after transaction", ex);
}
if (txObject.isNewConnectionHolder()) {
if (logger.isDebugEnabled()) {
logger.debug("Releasing JDBC Connection [" + con + "] after transaction");
}
DataSourceUtils.releaseConnection(con, this.dataSource);
}
// 将holder里的属性重置
txObject.getConnectionHolder().clear();
}
2.5.2、回顾transaction几个关键点!
txObject.isNewConnectionHolder()
如果transaction是一个新的holder,将此holder从当前线程解绑!
这里需要了解一个关键线程类,专门存放线程级别的变量TransactionSynchronizationManager
。
2.6、如果有挂起的事务,恢复它!
如果有挂起的事务的话,status.getSuspendedResources() != null
,也就是说status中会有suspendedResources这个属性,取得status中的transaction后进入resume方法:
protected final void resume(@Nullable Object transaction, @Nullable SuspendedResourcesHolder resourcesHolder)
throws TransactionException {
if (resourcesHolder != null) {
Object suspendedResources = resourcesHolder.suspendedResources;
// 如果有被挂起的事务才进入
if (suspendedResources != null) {
// 真正去resume恢复的地方
doResume(transaction, suspendedResources);
}
List<TransactionSynchronization> suspendedSynchronizations = resourcesHolder.suspendedSynchronizations;
if (suspendedSynchronizations != null) {
// 将上面提到的TransactionSynchronizationManager专门存放线程变量的类中
// 的属性设置成被挂起事务的属性
TransactionSynchronizationManager.setActualTransactionActive(resourcesHolder.wasActive);
TransactionSynchronizationManager.setCurrentTransactionIsolationLevel(resourcesHolder.isolationLevel);
TransactionSynchronizationManager.setCurrentTransactionReadOnly(resourcesHolder.readOnly);
TransactionSynchronizationManager.setCurrentTransactionName(resourcesHolder.name);
doResumeSynchronization(suspendedSynchronizations);
}
}
}
@Override
protected void doResume(@Nullable Object transaction, Object suspendedResources) {
TransactionSynchronizationManager.bindResource(obtainDataSource(), suspendedResources);
}
这里恢复只是把suspendedResources
重新绑定到线程中。
2.7、线程变量的绑定与解绑
上面已经提到有两个地方用到关于线程变量TransactionSynchronizationManager
的绑定与解绑了,在这里详细介绍一下绑定解绑到底是干嘛的,为什么要这么做。
绑定与解绑围绕一个线程变量,此变量在TransactionSynchronizationManager
类中:
private static final ThreadLocal<Map<Object, Object>> resources =
new NamedThreadLocal<>("Transactional resources");
2.7.1、绑定
public static void bindResource(Object key, Object value) throws IllegalStateException {
// 从上面可知,线程变量是一个Map,而这个Key就是dataSource
// 这个value这里剧透一下就是holder,在创建事务时会再次提到
Object actualKey = TransactionSynchronizationUtils.unwrapResourceIfNecessary(key);
Assert.notNull(value, "Value must not be null");
// 获取这个线程变量Map
Map<Object, Object> map = resources.get();
// set ThreadLocal Map if none found
if (map == null) {
map = new HashMap<>();
resources.set(map);
}
// 将新的holder作为value,dataSource作为key放入当前线程Map中
Object oldValue = map.put(actualKey, value);
// Transparently suppress a ResourceHolder that was marked as void...
if (oldValue instanceof ResourceHolder && ((ResourceHolder) oldValue).isVoid()) {
oldValue = null;
}
if (oldValue != null) {
throw new IllegalStateException("Already value [" + oldValue + "] for key [" +
actualKey + "] bound to thread [" + Thread.currentThread().getName() + "]");
} Thread.currentThread().getName() + "]");
}
// 略...
}
2.7.2、解绑
/**
* Actually remove the value of the resource that is bound for the given key.
*/
@Nullable
private static Object doUnbindResource(Object actualKey) {
// 取得当前线程的线程变量Map
Map<Object, Object> map = resources.get();
if (map == null) {
return null;
}
// 将key为dataSourece的value移除出Map,然后将旧的Holder返回
Object value = map.remove(actualKey);
// Remove entire ThreadLocal if empty...
// 如果此时map为空,直接清除线程变量
if (map.isEmpty()) {
resources.remove();
}
// Transparently suppress a ResourceHolder that was marked as void...
if (value instanceof ResourceHolder && ((ResourceHolder) value).isVoid()) {
value = null;
}
if (value != null && logger.isTraceEnabled()) {
logger.trace("Removed value [" + value + "] for key [" + actualKey + "] from thread [" +
Thread.currentThread().getName() + "]");
}
// 将旧Holder返回
return value;
}
这里绑定与解绑只需要知道,只是在TransactionSynchronizationManager
类中线程变量Map中进行添加与移除的操作而已,具体在哪里需要用到在介绍创建事务会提到。
2.8、神秘又关键的status对象
这里简要说明一下status
对象的结构,下面会有很多分支会频繁封装一些信息成status
对象
// 这里是构造一个status对象的方法
protected DefaultTransactionStatus newTransactionStatus(
TransactionDefinition definition, @Nullable Object transaction, boolean newTransaction,
boolean newSynchronization, boolean debug, @Nullable Object suspendedResources) {
boolean actualNewSynchronization = newSynchronization &&
!TransactionSynchronizationManager.isSynchronizationActive();
return new DefaultTransactionStatus(
transaction, newTransaction, actualNewSynchronization,
definition.isReadOnly(), debug, suspendedResources);
}
简单了解一下关键参数即可:
- 第二个参数
transaction
:事务对象,在一开头就有创建,其就是事务管理器的一个内部类。 - 第三个参数
newTransaction
:布尔值,一个标识,用于判断是否是新的事务,用于提交或者回滚方法中,是新的才会提交或者回滚。 - 最后一个参数
suspendedResources
:被挂起的对象资源,在前面挂起的介绍中也有说到,挂起操作会返回旧的holder
,将其与一些事务属性一起封装成一个对象,就是这个suspendedResources
这个对象了,它会放在status
中,在开头的清理工作方法中判断status中是否有这个挂起对象,如果有会恢复它。
2.9、创建事务Info对象
至此已经介绍完事务的大致流程了,主要主干如下
- 创建事务Info对象,下面几个步骤都要围绕事务Info对象展开
- 如有异常,根据Info中status状态判断回滚或提交或其他操作
- 如无异常,准备提交也要根据Info中status进行判断正常提交还是会回滚
- 流程结束,可知无论是有异常还是无异常都会进入完善收尾工作,在收尾过程如果是新的Holder将会进行解绑。如果status中存在被挂起的事务,会恢复它,具体恢复其实就是解绑操作。
从以上流程可以看出,事务Info占据了主要地位,它决定了所有步骤的走向,那么是如何创建一个事务Info的呢?
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) {
// 这里取得事务的status
status = tm.getTransaction(txAttr);
}
else {
if (logger.isDebugEnabled()) {
logger.debug("Skipping transactional joinpoint [" + joinpointIdentification +
"] because no transaction manager has been configured");
}
}
}
// 将得到的status与事务管理器,事务属性,事务名称一起封装成一个事务Info
return prepareTransactionInfo(tm, txAttr, joinpointIdentification, status);
}
其中核心是在getTransaction方法中:
@Override
public final TransactionStatus getTransaction(@Nullable TransactionDefinition definition) throws TransactionException {
// 获取一个transaction
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();
}
// 如果在这之前已经存在事务了,就进入存在事务的方法中
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());
}
// No existing transaction found -> check propagation behavior to find out how to proceed.
// 走到这里说明此时没有存在事务,如果传播特性是MANDATORY时抛出异常
if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_MANDATORY) {
throw new IllegalTransactionStateException(
"No existing transaction found for transaction marked with propagation 'mandatory'");
}
// 如果此时不存在事务,当传播特性是REQUIRED或NEW或NESTED都会进入if语句块
else if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRED ||
definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRES_NEW ||
definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NESTED) {
// 因为此时不存在事务,将null挂起
SuspendedResourcesHolder suspendedResources = suspend(null);
if (debugEnabled) {
logger.debug("Creating new transaction with name [" + definition.getName() + "]: " + definition);
}
try {
boolean newSynchronization = (getTransactionSynchronization() != SYNCHRONIZATION_NEVER);
// new一个status,存放刚刚创建的transaction,然后将其标记为新事务!
// 这里transaction后面一个参数决定是否是新事务!
DefaultTransactionStatus status = newTransactionStatus(
definition, transaction, true, newSynchronization, debugEnabled, suspendedResources);
// 新开一个连接的地方
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);
}
// 其他的传播特性一律返回一个空事务,transaction = null
boolean newSynchronization = (getTransactionSynchronization() == SYNCHRONIZATION_ALWAYS);
return prepareTransactionStatus(definition, null, true, newSynchronization, debugEnabled, null);
}
}
先来看看transaction是如何被创建出来的:
@Override
protected Object doGetTransaction() {
// 这里DataSourceTransactionObject是事务管理器的一个内部类
// DataSourceTransactionObject就是一个transaction,这里new了一个出来
DataSourceTransactionObject txObject = new DataSourceTransactionObject();
txObject.setSavepointAllowed(isNestedTransactionAllowed());
// 解绑与绑定的作用在此时体现,如果当前线程有绑定的话,将会取出holder
ConnectionHolder conHolder =
(ConnectionHolder) TransactionSynchronizationManager.getResource(obtainDataSource());
// 此时的holder被标记成一个旧holder
txObject.setConnectionHolder(conHolder, false);
return txObject;
}
创建transaction过程很简单,接着就会判断当前是否存在事务:
@Override
protected boolean isExistingTransaction(Object transaction) {
DataSourceTransactionObject txObject = (DataSourceTransactionObject) transaction;
return (txObject.hasConnectionHolder() && txObject.getConnectionHolder().isTransactionActive());
}
这里判断是否存在事务的依据主要是获取holder中的transactionActive
变量是否为true,如果是第一次进入事务,holder直接为null判断不存在了,如果是第二次进入事务transactionActive
变量是为true的(后面会提到是在哪里把它变成true的),由此来判断当前是否已经存在事务了。
2.9.1、什么是挂起事务的操作?
上面已经有提到挂起了,当传播特性是REQUIRED或NEW或NESTED时将会挂起,那么挂起做了什么呢?
@Nullable
protected final SuspendedResourcesHolder suspend(@Nullable Object transaction) throws TransactionException {
if (TransactionSynchronizationManager.isSynchronizationActive()) {
List<TransactionSynchronization> suspendedSynchronizations = doSuspendSynchronization();
try {
Object suspendedResources = null;
if (transaction != null) {
// 这里是真正做挂起的方法,这里返回的是一个holder
suspendedResources = doSuspend(transaction);
}
// 这里将名称、隔离级别等信息从线程变量中取出并设置对应属性为null到线程变量
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);
// 将事务各个属性与挂起的holder一并封装进SuspendedResourcesHolder对象中
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;
}
}
@Override
protected Object doSuspend(Object transaction) {
DataSourceTransactionObject txObject = (DataSourceTransactionObject) transaction;
// 将transaction中的holder属性设置为空
txObject.setConnectionHolder(null);
// 解绑!
return TransactionSynchronizationManager.unbindResource(obtainDataSource());
}
如果忘记解绑是干什么的,可以回头看一下解绑操作的介绍。这里挂起主要干了三件事:
- 将
transaction
中的holder属性设置为空 - 解绑(会返回线程中的那个旧的holder出来,从而封装到
SuspendedResourcesHolder
对象中) - 将
SuspendedResourcesHolder
放入status中
2.9.2、当前不存在事务的情况
从上面的注解也可以很清楚知道,如果不存在事务,传播特性又是REQUIRED或NEW或NESTED,将会先挂起,然后执行一个方法,doBegin(transaction, definition); 这个方法也是一个关键方法:
@Override
protected void doBegin(Object transaction, TransactionDefinition definition) {
DataSourceTransactionObject txObject = (DataSourceTransactionObject) transaction;
Connection con = null;
try {
// 判断如果transaction没有holder的话,才去从dataSource中获取一个新连接
if (!txObject.hasConnectionHolder() ||
txObject.getConnectionHolder().isSynchronizedWithTransaction()) {
Connection newCon = obtainDataSource().getConnection();
if (logger.isDebugEnabled()) {
logger.debug("Acquired Connection [" + newCon + "] for JDBC transaction");
}
// 所以,只有transaction中的holder为空时,才会设置为新holder
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");
}
// 将此新连接取消自动提交,改由Spring控制事务的提交
con.setAutoCommit(false);
}
prepareTransactionalConnection(con, definition);
// 在这里就是之前说的判断当时是否有事务的依据,新创建的holder将会设置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.
// 开头有提到,如果transaction中holder=null的话就是新的holder了
// 如果此时是新创建出来的holder的话,绑定!
if (txObject.isNewConnectionHolder()) {
TransactionSynchronizationManager.bindResource(obtainDataSource(), txObject.getConnectionHolder());
}
}
// 略...
}
在这个方法中,几乎呼应了很多很多上文存在的疑惑。
- 何时active=true?:执行doBegin方法时,都会将transaction中的holder设置active=true
- 何时holder是新的?:当transaction中的holder=null时,才会新创一个connection然后去new一个holder,然后将新connection放入holder,再将holder放入transaction并设置其为新的holder
- txObject.isNewConnectionHolder():如果是新的holder,将会把holder绑定到当前线程,这里可以知道,绑定操作其实绑定的类是一个holder
2.9.3、小结
- REQUIRED或NEW或NESTED :挂起一个null(挂起null时将不会解绑,其实也不用解绑,此时线程变量也根本不存在holder,transaction中的holder也是null,这里非要挂起一个null是为了提取出其他事务的信息封装进
SuspendedResourcesHolder
对象中),执行doBegin方法,标记为新事务,封装status
对象:
DefaultTransactionStatus status = newTransactionStatus(
definition, transaction, true, newSynchronization, debugEnabled, suspendedResources);
当不存在事务时,传播特性又是REQUIRED或NEW或NESTED时,注意此时线程并没有任何绑定操作,所以线程变量Map里的value其实是空的,此时new出来的transaction中的holder其实是null,当执行doBegin方法时,会创建一个新的holder与新的connection,然后做绑定操作,此时线程变量Map就会有了这个holder了!同时设置此时的transaction的holder为新的,hoder的active将为true。
doBegin方法其实就是在设置transaction
中的holder
,然后返回一个处理好的transaction
封装给status,给一开始的地方使用。
2.9.4、当前存在事务的情况
前面已经提到,第一次事务开始时必会新创一个holder然后做绑定操作,此时线程变量是有holder的且avtive为true,如果第二个事务进来,去new一个transaction之后去线程变量中取holder,holder是不为空的且active是为true的,所以会进入handleExistingTransaction方法:
/**
* Create a TransactionStatus for an existing transaction.
*/
private TransactionStatus handleExistingTransaction(
TransactionDefinition definition, Object transaction, boolean debugEnabled)
throws TransactionException {
// 如果传播特性是NEVER,当前又存在了事务了,抛出异常
if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NEVER) {
throw new IllegalTransactionStateException(
"Existing transaction found for transaction marked with propagation 'never'");
}
// 如果传播特性是NOT_SUPPORTED,仅仅是不给他支持,就返回一个空事务
if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NOT_SUPPORTED) {
if (debugEnabled) {
logger.debug("Suspending current transaction");
}
// 这里会将原来的事务挂起
Object suspendedResources = suspend(transaction);
boolean newSynchronization = (getTransactionSynchronization() == SYNCHRONIZATION_ALWAYS);
// 这里可以看到,第二个参数transaction传了一个空事务,第三个参数false为旧标记
// 最后一个参数就是前面挂起提到的最终封装后的对象一起封装成status返回给前面
return prepareTransactionStatus(
definition, null, false, newSynchronization, debugEnabled, suspendedResources);
}
// 如果此时传播特性是REQUIRES_NEW,此时会新建一个事务
if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRES_NEW) {
if (debugEnabled) {
logger.debug("Suspending current transaction, creating new transaction with name [" +
definition.getName() + "]");
}
// 将原事务挂起,此时新建事务,不与原事务有关系
// 会将transaction中的holder设置为null,然后解绑!(建议回顾一下挂起做了什么事)
SuspendedResourcesHolder suspendedResources = suspend(transaction);
try {
boolean newSynchronization = (getTransactionSynchronization() != SYNCHRONIZATION_NEVER);
// new一个status出来,传入transaction,并且为新事务标记,然后传入挂起事务
DefaultTransactionStatus status = newTransactionStatus(
definition, transaction, true, newSynchronization, debugEnabled, suspendedResources);
// 这里也做了一次doBegin,此时的transaction中holer是为空的,因为之前被挂起了
// 所以这里会取一次新的连接,并且绑定!
doBegin(transaction, definition);
prepareSynchronization(status, definition);
return status;
}
catch (RuntimeException | Error beginEx) {
resumeAfterBeginException(transaction, suspendedResources, beginEx);
throw beginEx;
}
}
// 如果此时的传播特性是NESTED,不会挂起事务
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() + "]");
}
// 这里如果是JTA事务管理器,就不可以用savePoint了,将不会进入此方法
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.
// 这里不会挂起事务,说明NESTED的特性是原事务的子事务而已
// new一个status,传入transaction,传入旧事务标记,传入挂起对象=null
DefaultTransactionStatus status =
prepareTransactionStatus(definition, transaction, false, false, debugEnabled, null);
// 这里是NESTED特性特殊的地方,在先前存在事务的情况下会建立一个savePoint
status.createAndHoldSavepoint();
return status;
}
else {
// 这里是JTA事务管理器会进入的方法
// 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;
}
}
// 中间一大段代码略....
boolean newSynchronization = (getTransactionSynchronization() != SYNCHRONIZATION_NEVER);
// 这里如果是其他的传播特性的话,例如REQUIRED,直接运行在当前事务中了
// new一个status,设置transaction,标记为旧事务,空挂起
return prepareTransactionStatus(definition, transaction, false, newSynchronization, debugEnabled, null);
}
2.9.5、小结
到这里我们可以知道,在当前存在事务的情况下,根据传播特性去决定是否为新事务,是否挂起当前事务。
- NOT_SUPPORTED :会挂起事务,不运行doBegin方法传空
transaction
,标记为旧事务。封装status
对象:
return prepareTransactionStatus(
definition, null, false, newSynchronization, debugEnabled, suspendedResources)
- REQUIRES_NEW :将会挂起事务且运行doBegin方法,标记为新事务。封装
status
对象:
DefaultTransactionStatus status = newTransactionStatus(
definition, transaction, true, newSynchronization, debugEnabled, suspendedResources);
- NESTED :不会挂起事务且不会运行doBegin方法,标记为旧事务,但会创建savePoint。封装
status
对象:
DefaultTransactionStatus status =
prepareTransactionStatus(definition, transaction, false, false, debugEnabled, null);
- 其他事务例如REQUIRED :不会挂起事务,不会运行doBegin方法,标记旧事务,封装
status
对象:
return prepareTransactionStatus(definition, transaction, false, newSynchronization, debugEnabled, null);
3、总结
这篇文章主要讲解了事务增强器大致的脉络,增强器是实现事务功能的核心类,理解了TransactionInterceptor的invoke方法干了什么,就大概可以知道Spring事务的原理了。其中讲解了几个小模块:
status
对象的封装,何时会封装成新事务- 挂起到底做了什么,何时会挂起,何时会恢复
- 绑定与解绑又是做了什么
- 各种传播特性在各种场景下的表现,例如是否会doBegin、是否新事务标记、是否挂起等
文章到了这里,也基本介绍完事务增强器的作用了,本文花了这么大篇幅才把这一个增强器讲完。。。本来还计划讲完增强器之后结合传播特性分析传播特性的实现原理,但没想到事务增强器原来可以写这么多东西,由于篇幅问题,其他内容将在下一篇文章中会提到。
在下一篇文章中会用实验流程去解释以上包括挂起、恢复、绑定、解绑、doBegin等的具体作用,以及用实例去告诉读者,各类传播特性到底是怎么回事,以及如何在同类中事务方法调用同类事务方法。