这里接上一篇 Spring之事务注解@Transactional解析(一)来分析下Transactionlnterceptor 的事务增强逻辑。
入口在 Transactionlnterceptor 类的 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);
// return invokeWithinTransaction(invocation.getMethod(), targetClass, new InvocationCallback() {
// @Override
// //InvocationCallback接口的回调方法
// public Object proceedWithInvocation() throws Throwable {
// //执行目标方法
// return invocation.proceed();
// }
// });
return invokeWithinTransaction(invocation.getMethod(), targetClass, invocation::proceed);
}
调用父类TransactionAspectSupport的invokeWithinTransaction方法
@Nullable
protected Object invokeWithinTransaction(Method method, @Nullable Class<?> targetClass,
final InvocationCallback invocation) throws Throwable {
// 1、获取事务属性源(如果事务属性为空,则该方法是非事务性的)
TransactionAttributeSource tas = getTransactionAttributeSource();
// 2、得到事务属性
final TransactionAttribute txAttr = (tas != null ? tas.getTransactionAttribute(method, targetClass) : null);
// 3、从容器中获取到PlatformTransactionManager,
// Spring框架并不直接管理事务,而是通过这个接口为不同的持久层框架提供了不同的
// PlatformTransactionManager接口实现类,也就是将事务管理的职责委托给
// Hibernate或者iBatis等持久化框架的事务来实现
final PlatformTransactionManager tm = determineTransactionManager(txAttr);
// 4、目标方法唯一标识,包名 + 类名 + 方法名
final String joinpointIdentification = methodIdentification(method, targetClass, txAttr);
// 5、声明式事务
if (txAttr == null || !(tm instanceof CallbackPreferringPlatformTransactionManager)) {
// 5.1、看是否有必要创建一个事务(其实事务对象都是新建,主要是里面的连接是否是新的),
// 根据事务传播行为决定
// 这里的TransactionInfo是新建的
TransactionInfo txInfo = createTransactionIfNecessary(tm, txAttr, joinpointIdentification);
Object retVal;
try {
// This is an around advice: Invoke the next interceptor in the chain.
// This will normally result in a target object being invoked.
// 5.2、调用目标方法,一般就是业务层的方法,操作数据库。
// 这其实是一个环绕通知,调用目标方法先开启事务,执行完目标方法后在下面提交事务
retVal = invocation.proceedWithInvocation();
}
catch (Throwable ex) {
// 5.3、异常回滚事务
completeTransactionAfterThrowing(txInfo, ex);
throw ex;
}
finally {
// 5.4、不管最终执行如何,都要清除事务信息
cleanupTransactionInfo(txInfo);
}
// 5.5、提交事务
commitTransactionAfterReturning(txInfo);
return retVal;
}
// 6、编程式事务
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、获取到目标方法的事务属性TransactionAttribute,从缓存中获取;
3、从容器中获取到PlatformTransactionManager,先从缓存中获取,没取到就从spring容器中获取;
PlatformTransactionManager是spring的事务管理器接口,spring并不直接管理事务,而是通过这个接口为不同的持久层框架提供了不同的PlatformTransactionManager接口实现类,也就是将事务管理的职责委托给Hibernate或者MyBatis等持久化框架的事务来实现。
org.springframework.jdbc.datasource.DataSourceTransactionManager:使用JDBC或者iBatis进行持久化数据时使用
org.springframework.orm.hibernate5.HibernateTransactionManager:使用hibernate5版本进行持久化数据时使用
org.springframework.orm.jpa.JpaTransactionManager:使用JPA进行持久化数据时使用
org.springframework.jdo.JdoTransactionManager:当持久化机制是jdo时使用
org.springframework.transaction.jta.JtaTransactionManager:使用一个JTA实现来管理事务,在一个事务跨越多个资源时必须使用
PlatformTransactionManager接口源码:
public interface PlatformTransactionManager {
//事务管理器通过TransactionDefinition,获得“事务状态”,从而管理事务
TransactionStatus getTransaction(@Nullable TransactionDefinition definition)
throws TransactionException;
//根据状态提交
void commit(TransactionStatus status) throws TransactionException;
//根据状态回滚
void rollback(TransactionStatus status) throws TransactionException;
}
4、获取目标方法的唯一标识,包名 + 类名 + 方法名;
5、处理声明式事务;
这里只关注声明式事务。
创建事务
5.1、先看是否有必要创建一个事务,根据事务传播行为决定,所以txInfo里可能包含一个外层的事务/新建的事务/没有事务。TransactionInfo是TransactionAspectSupport类的内部类,用来保存事务相关信息。
TransactionInfo源码:
protected final class TransactionInfo {
@Nullable
private final PlatformTransactionManager transactionManager;
@Nullable
private final TransactionAttribute transactionAttribute;
private final String joinpointIdentification;
@Nullable
private TransactionStatus transactionStatus;
@Nullable
private TransactionInfo oldTransactionInfo;
// ......
}
protected TransactionInfo createTransactionIfNecessary(@Nullable PlatformTransactionManager tm,
@Nullable TransactionAttribute txAttr, final String joinpointIdentification) {
// 如果未指定名称,则应用方法标识作为事务名称
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) {
// 从事务管理器中获取TransactionStatus,根据指定的传播行为返回当前的事务或创建新事务
// TransactionStatus是新建的
status = tm.getTransaction(txAttr);
}
else {
if (logger.isDebugEnabled()) {
logger.debug("Skipping transactional joinpoint [" + joinpointIdentification +
"] because no transaction manager has been configured");
}
}
}
// 为给定的属性和状态对象准备一个 TransactionInfo
return prepareTransactionInfo(tm, txAttr, joinpointIdentification, status);
}
这里主要就是从事务管理器中获取TransactionStatus,根据指定的传播行为返回当前的事务或创建新事务。
TransactionStatus表示一个具体的事务状态。
public interface TransactionStatus extends SavepointManager, Flushable {
/**
* 返回当前事务是否是新的
*/
boolean isNewTransaction();
/**
* 返回事务内部是否有保存点
*/
boolean hasSavepoint();
/**
* 设置事务仅回滚
*/
void setRollbackOnly();
/**
* 返回事务是否已被标记为仅回滚
*/
boolean isRollbackOnly();
/**
* 将底层会话刷新到数据存储区
*/
@Override
void flush();
/**
* 返回此事务是否完成,即是否已经提交或回滚
*/
boolean isCompleted();
}
它的默认实现是DefaultTransactionStatus,里面包含一个事务对象以及挂起的资源。
public class DefaultTransactionStatus extends AbstractTransactionStatus {
// 事务对象
@Nullable
private final Object transaction;
private final boolean newTransaction;
private final boolean newSynchronization;
private final boolean readOnly;
private final boolean debug;
@Nullable
private final Object suspendedResources;
}
@Override
public final TransactionStatus getTransaction(@Nullable TransactionDefinition definition) throws TransactionException {
// 获取transaction对象,
// 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);
}
// 在创建新事务之前先检查下事务属性是否正确
if (definition.getTimeout() < TransactionDefinition.TIMEOUT_DEFAULT) {// 超时时间是否设置正确
throw new InvalidTimeoutException("Invalid transaction timeout", definition.getTimeout());
}
// 检查传播行为,如果是PROPAGATION_MANDATORY则抛异常,因为PROPAGATION_MANDATORY表示当前必须存在事务,如果当前不存在事务,则抛出异常
if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_MANDATORY) {
throw new IllegalTransactionStateException(
"No existing transaction found for transaction marked with propagation 'mandatory'");
}
// 在当前不存在事务的情况下,这3个都是创建一个新的事务
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);
DefaultTransactionStatus status = newTransactionStatus(
definition, transaction, true, newSynchronization, debugEnabled, suspendedResources);// 创建一个新的TransactionStatus,其中的true代表的是新的事务
// 开启一个新事务
doBegin(transaction, definition);
// 为TransactionSynchronizationManager的ThreadLocal绑定数据,
// 在事务完成后清除绑定
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);
}
}
DataSourceTransactionManager
@Override
protected Object doGetTransaction() {
// 创建一个事务对象
DataSourceTransactionObject txObject = new DataSourceTransactionObject();
txObject.setSavepointAllowed(isNestedTransactionAllowed());
// 根据数据源获取到当前的ConnectionHolder,因为有时候会配置多数据源。刚开始从缓存中获取到的肯定是空的
ConnectionHolder conHolder =
(ConnectionHolder) TransactionSynchronizationManager.getResource(obtainDataSource());
// 往事务对象中设置ConnectionHolder
// 这里newConnectionHolder是先设置成false,后面再重新判断设置
txObject.setConnectionHolder(conHolder, false);
return txObject;
}
DataSourceTransactionObject
DataSourceTransactionObject是DataSourceTransactionManager事务管理器的内部类,代表事务对象,里面持有.
数据库连接,对于是否是同一个事务,就看事务对象持有的连接是否一样。
TransactionSynchronizationManager
public abstract class TransactionSynchronizationManager {
private static final Log logger = LogFactory.getLog(TransactionSynchronizationManager.class);
// 存放当前线程不同数据源的连接,<DataSource:ConnectionHolder>
private static final ThreadLocal<Map<Object, Object>> resources =
new NamedThreadLocal<>("Transactional resources");
// 事务同步器,是Spring交由程序员进行扩展的代码,每个线程可以注册N个事务同步器
private static final ThreadLocal<Set<TransactionSynchronization>> synchronizations =
new NamedThreadLocal<>("Transaction synchronizations");
// 事务的名称
private static final ThreadLocal<String> currentTransactionName =
new NamedThreadLocal<>("Current transaction name");
// 事务是否是只读
private static final ThreadLocal<Boolean> currentTransactionReadOnly =
new NamedThreadLocal<>("Current transaction read-only status");
// 事务的隔离级别
private static final ThreadLocal<Integer> currentTransactionIsolationLevel =
new NamedThreadLocal<>("Current transaction isolation level");
// 事务是否开启
private static final ThreadLocal<Boolean> actualTransactionActive =
new NamedThreadLocal<>("Actual transaction active");
@Nullable
public static Object getResource(Object key) {
Object actualKey = TransactionSynchronizationUtils.unwrapResourceIfNecessary(key);// 根据需要对key进行包装
// 获取到当前数据源的连接
Object value = doGetResource(actualKey);
if (value != null && logger.isTraceEnabled()) {
logger.trace("Retrieved value [" + value + "] for key [" + actualKey + "] bound to thread [" +
Thread.currentThread().getName() + "]");
}
return value;
}
@Nullable
private static Object doGetResource(Object actualKey) {
// 先获取到当前线程的资源
Map<Object, Object> map = resources.get();
if (map == null) {
return null;
}
// 再获取对应数据源的连接
Object value = map.get(actualKey);
// Transparently remove ResourceHolder that was marked as void...
if (value instanceof ResourceHolder && ((ResourceHolder) value).isVoid()) {
map.remove(actualKey);
// Remove entire ThreadLocal if empty...
if (map.isEmpty()) {
resources.remove();
}
value = null;
}
return value;
}
}
然后根据事务对象判断当前是否已经存在一个事务了
@Override
protected boolean isExistingTransaction(Object transaction) {
DataSourceTransactionObject txObject = (DataSourceTransactionObject) transaction;
return (txObject.hasConnectionHolder() && txObject.getConnectionHolder().isTransactionActive());
}
就是看事务对象中的connectionHolder是否为空以及connectionHolder中的属性transactionActive是否是true。
这里分为两种情况,先看当前没有事务的情况。
当前没有事务
如果还没有事务,事务对象中的connectionHolder还是空的,则需要创建一个新的事务。
在创建事务之前会先检查下事务属性是否正确,因为如果传播行为是PROPAGATION_MANDATORY的话当前必须存在事务,那这里不存在事务就会抛出异常。
如果传播行为不是PROPAGATION_MANDATORY还要再判断是否是PROPAGATION_REQUIRED、PROPAGATION_REQUIRES_NEW以及PROPAGATION_NESTED,因为只有这3个在当前不存在事务时才会去创建一个新的事务。
在开启新事务之前需要先创建一个TransactionStatus,里面包含事务对象,事务对象里的事务持有者还是null
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);
}
其中newTransaction为true,代表是一个新的事务。
然后通过doBegin开启一个事务,主要就是从数据源中获取一个Connection设置到事务对象中,设置事务属性以及绑定Connection到当前线程。
@Override
protected void doBegin(Object transaction, TransactionDefinition definition) {
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");
}
// 为给定的连接创建一个新的 ConnectionHolder,用SimpleConnectionHandle包装它,
// 并且在这里将事务对象中的newConnectionHolder属性设为true,表示是新建的
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事务就是将事务设置为手动提交,由spring进行控制
con.setAutoCommit(false);
}
// 准备事务连接,主要是对只读事务
prepareTransactionalConnection(con, definition);
// 设置transactionActive为true
txObject.getConnectionHolder().setTransactionActive(true);
// 设置事务超时时间
int timeout = determineTimeout(definition);
if (timeout != TransactionDefinition.TIMEOUT_DEFAULT) {
txObject.getConnectionHolder().setTimeoutInSeconds(timeout);
}
// 将 connection holder 绑定到当前线程,如果下次调用就知道当前存在事务了
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);
}
}
最后将给定的属性和状态对象封装为一个 TransactionInfo返回回去
protected TransactionInfo prepareTransactionInfo(@Nullable PlatformTransactionManager tm,
@Nullable TransactionAttribute txAttr, String joinpointIdentification,
@Nullable TransactionStatus status) {
// 新建一个TransactionInfo
TransactionInfo txInfo = new TransactionInfo(tm, txAttr, joinpointIdentification);
if (txAttr != null) {
// We need a transaction for this method...
if (logger.isTraceEnabled()) {
logger.trace("Getting transaction for [" + txInfo.getJoinpointIdentification() + "]");
}
// The transaction manager will flag an error if an incompatible tx already exists.
// 设置txInfo的事务状态
txInfo.newTransactionStatus(status);
}
else {
// The TransactionInfo.hasTransaction() method will return false. We created it only
// to preserve the integrity of the ThreadLocal stack maintained in this class.
if (logger.isTraceEnabled()) {
logger.trace("No need to create transaction for [" + joinpointIdentification +
"]: This method is not transactional.");
}
}
// 总是将 TransactionInfo 绑定到线程,即使没有在这里创建新事务
txInfo.bindToThread();
return txInfo;
}
在将事务信息绑定到当前线程的同时,保存先前的事务信息,以便可能在后面将事务信息重置到之前的状态
private void bindToThread() {
// Expose current TransactionStatus, preserving any existing TransactionStatus
// for restoration after this transaction is complete.
this.oldTransactionInfo = transactionInfoHolder.get();
transactionInfoHolder.set(this);
}
以上是当前没有事务时创建一个新事务时的逻辑,下面看下如果当前已经存在事务,那是如何加入当前的事务的
当前存在事务
若当前存在事务,在创建事务对象时,从TransactionSynchronizationManager获取到的ConnectionHolder就不是空的,里面包含当前事务的连接,并且连接时活跃的。
所以在判断当前是否存在事务时,才会返回true
@Override
protected boolean isExistingTransaction(Object transaction) {
DataSourceTransactionObject txObject = (DataSourceTransactionObject) transaction;
return (txObject.hasConnectionHolder() && txObject.getConnectionHolder().isTransactionActive());
}
这里的两个判断txObject.hasConnectionHolder()和txObject.getConnectionHolder().isTransactionActive()都为true。
接下来即看如何处理
private TransactionStatus handleExistingTransaction(
TransactionDefinition definition, Object transaction, boolean debugEnabled)
throws TransactionException {
// 1、PROPAGATION_NEVER代表始终以非事务执行;如果当前存在事务,则抛出异常
if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NEVER) {
throw new IllegalTransactionStateException(
"Existing transaction found for transaction marked with propagation 'never'");
}
// 2、始终以非事务执行,不管当前存不存在事务
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);
}
// 3、创建一个新事务,如果当前存在一个事务则挂起当前事务
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就是去获取一个新的连接,以创建一个新的事务
doBegin(transaction, definition);
// 初始化事务同步
prepareSynchronization(status, definition);
return status;
}
catch (RuntimeException | Error beginEx) {
resumeAfterBeginException(transaction, suspendedResources, beginEx);
throw beginEx;
}
}
// 4、嵌套事务
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;
}
}
// 5、PROPAGATION_SUPPORTS(当前存在事务,则加入该事务;如果不存在,则以非事务方式执行)
// 或 PROPAGATION_REQUIRED(当前存在事务,则加入该事务,如果不存在,则创建一个新的(默认))
if (debugEnabled) {
logger.debug("Participating in existing transaction");
}
// 在加入当前事务之前是否应该对其验证,默认是false
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);
// 这里newTransaction传false,表示不是新的事务,而是加入现有的事务
return prepareTransactionStatus(definition, transaction, false, newSynchronization, debugEnabled, null);
}
这里也根据不同的传播行为进行不同的处理
1、PROPAGATION_NEVER 代表始终以非事务执行;如果当前存在事务,则抛出异常。
2、PROPAGATION_NOT_SUPPORTED 代表始终以非事务执行,不管当前存不存在事务。如果当前存在事务,则将该事务挂起。看下如何挂起事务。
暂停给定的事务。首先暂停事务同步,然后委托给doSuspend模板方法。
protected final SuspendedResourcesHolder suspend(@Nullable Object transaction) throws TransactionException {
// 如果是事务同步中
if (TransactionSynchronizationManager.isSynchronizationActive()) {
// 暂停事务同步
List<TransactionSynchronization> suspendedSynchronizations = doSuspendSynchronization();
try {
Object suspendedResources = null;
// 事务对象不为空时,调用doSuspend挂起当前事务,返回connectionHolder对象
if (transaction != null) {
suspendedResources = doSuspend(transaction);
}
// 将TransactionSynchronizationManager中绑定的信息提出来封装到SuspendedResourcesHolder中,然后解绑
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);
// 将挂起的连接资源和事务同步器封装到SuspendedResourcesHolder,用于后面的恢复操作
return new SuspendedResourcesHolder(
suspendedResources, suspendedSynchronizations, name, readOnly, isolationLevel, wasActive);
}
catch (RuntimeException | Error ex) {
// 挂起失败,则恢复事务同步
doResumeSynchronization(suspendedSynchronizations);
throw ex;
}
}
else if (transaction != null) {
// 事务是活动的但没有事务同步,则就直接挂起事务,没有暂停事务同步操作
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;
// 将事务对象的connectionHolder属性置空,表示当前没有事务,
// 因为有事务就是事务对象中持有连接
txObject.setConnectionHolder(null);
// 将当前的线程的连接(connectionHolder)解绑,返回connectionHolder对象
return TransactionSynchronizationManager.unbindResource(obtainDataSource());
}
挂起事务主要就是记录原有事务的状态,以便于后续操作对事务的恢复。这里将connectionHolder属性置空,表示当前没有事务,这样下次需要使用时,得从缓存池中获取一个连接,新连接的自动提交是 true。
3、PROPAGATION_REQUIRES_NEW 表示总是创建一个新事务,如果当前存在一个事务则挂起当前事务。由于进入该方法都是当前存在事务的,所以这里会挂起当前事务然后创建一个新的事务。挂起事务的逻辑上面分析了,而挂起旧事务创建一个新的事务就相当于当前没有事务要创建一个新的事务一样,上面也分析了,所以这里就都不再重新分析了。
4、PROPAGATION_NESTED 表示如果当前存在事务,则在嵌套事务内执行。
5、PROPAGATION_SUPPORTS 和 PROPAGATION_REQUIRED 在当前存在事务的情况下都是加入该事务。
这里主要就看默认传播行为PROPAGATION_REQUIRED,则直接最后一行,去创建事务状态,注意这里newTransaction是false。
protected final DefaultTransactionStatus prepareTransactionStatus(
TransactionDefinition definition, @Nullable Object transaction, boolean newTransaction,
boolean newSynchronization, boolean debug, @Nullable Object suspendedResources) {
// 创建事务状态
DefaultTransactionStatus status = newTransactionStatus(
definition, transaction, newTransaction, newSynchronization, debug, suspendedResources);
// 这里事务状态的newSynchronization属性是false,所以不会再初始化事务同步,
// 还是与外层事务一致
prepareSynchronization(status, definition);
return status;
}
protected DefaultTransactionStatus newTransactionStatus(
TransactionDefinition definition, @Nullable Object transaction, boolean newTransaction,
boolean newSynchronization, boolean debug, @Nullable Object suspendedResources) {
// false
boolean actualNewSynchronization = newSynchronization &&
!TransactionSynchronizationManager.isSynchronizationActive();
// 创建事务状态
return new DefaultTransactionStatus(
transaction, newTransaction, actualNewSynchronization,
definition.isReadOnly(), debug, suspendedResources);
}
可以看到逻辑基本和当前没有事务时差不多,只是事务对象中的连接与外层事务相同以及newTransaction属性是false。
执行目标方法
5.2、处理完目标方法调用前的事务,就该调用目标方法了,操作数据库
这一步可以去看aop中调到目标方法的逻辑。
执行完目标方法后就需要根据执行的结果提交事务或回滚事务。
回滚事务
5.3、如果在执行目标方法的过程中抛出了异常,可能就需要回滚事务,当然也可能照常提交事务,根据配置的哪些异常需要回滚来决定。
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类型以及子类的异常才会回滚
if (txInfo.transactionAttribute != null && txInfo.transactionAttribute.rollbackOn(ex)) {
try {
// 事务回滚
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;
}
}
}
}
不是所有情况都会回滚的,默认情况下是RuntimeException或Error类型以及子类的异常才会回滚
public boolean rollbackOn(Throwable ex) {
return (ex instanceof RuntimeException || ex instanceof Error);
}
可以通过改变@Transactional注解的属性rollbackFor来改变需要回滚的异常
@Transactional(rollbackFor = Exception.class)
如果异常符合条件就会回滚,也是通过事务管理器来回滚
@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);
}
private void processRollback(DefaultTransactionStatus status, boolean unexpected) {
try {
boolean unexpectedRollback = unexpected;
try {
// 事务同步的回调
triggerBeforeCompletion(status);
// 1、如果有保存点则回滚到保存点,此时事务是子事务并且是NESTED类型
if (status.hasSavepoint()) {
if (status.isDebug()) {
logger.debug("Rolling back transaction to savepoint");
}
status.rollbackToHeldSavepoint();
}
// 2、是新建的事务才会回滚
else if (status.isNewTransaction()) {
if (status.isDebug()) {
logger.debug("Initiating transaction rollback");
}
// 调具体事务管理器来回滚事务
doRollback(status);
}
// 3、当前没有事务或是加入的外层事务
else {
// 加入外层的事务
if (status.hasTransaction()) {
// status.isLocalRollbackOnly()默认false,
// isGlobalRollbackOnParticipationFailure()默认true,在参与事务失败后将现有事务全局标记为仅回滚
// 所以这里默认就是true
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;
}
// 回调
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);
}
}
这里又会分成3种情况
1、第一种就是有保存点,这种情况下就是当前事务必须是子事务,并且事务传播类型是NESTED,是嵌套事务。
2、第二种就是当前事务是新建的事务,那哪些情况下事务是新建的?看下下面的事务传播行为类型说明发现就三个,第一个是REQUIRED如果当前没有事务,就新建一个事务,这个是外层事务;第二个是REQUIRES_NEW,总是新建事务,这个不管是哪层事务;第三个是NESTED,这个需要是最外层事务才是新建事务。
所以要回滚事务就需要是以上3种情况。
@Override
protected void doRollback(DefaultTransactionStatus status) {
DataSourceTransactionObject txObject = (DataSourceTransactionObject) status.getTransaction();
Connection con = txObject.getConnectionHolder().getConnection();
if (status.isDebug()) {
logger.debug("Rolling back JDBC transaction on Connection [" + con + "]");
}
try {
con.rollback();
}
catch (SQLException ex) {
throw new TransactionSystemException("Could not roll back JDBC transaction", ex);
}
}
最终底层就是调用Connection的rollback方法来回滚。
3、第三种就是除以上两种情况的其它情况,要么是以非事务执行,要么是加入外层事务,并非是新事务。
如果是加入外层事务,由于事务管理器中的globalRollbackOnParticipationFailure属性默认是true,并且spring没有修改,会执行下面的将事务标记为仅回滚,但不是真正的回滚。等到提交的时候再判断是否有回滚标识,如果有回滚标识,就执行回滚。(如果子事务抛出异常了,那外层事务也会抛出异常,那就直接到回滚逻辑了,不会到提交事务那里,那这里的说法是否正确??)
@Override
protected void doSetRollbackOnly(DefaultTransactionStatus status) {
DataSourceTransactionObject txObject = (DataSourceTransactionObject) status.getTransaction();
if (status.isDebug()) {
logger.debug("Setting JDBC transaction [" + txObject.getConnectionHolder().getConnection() +
"] rollback-only");
}
// 标记为仅回滚
txObject.setRollbackOnly();
}
public void setRollbackOnly() {
getConnectionHolder().setRollbackOnly();
}
将status中的Transaction中的 ConnectionHolder的属性rollbackOnly标记为true。
如果当前没有事务,那没有回滚相关的操作。
最后调用cleanupAfterCompletion执行当前事务完成后的情况工作,如有必要,还要恢复挂起的事务。
private void cleanupAfterCompletion(DefaultTransactionStatus status) {
// 设置当前事务已完成
status.setCompleted();
// 清理事务同步
if (status.isNewSynchronization()) {
TransactionSynchronizationManager.clear();
}
// 如果是新事务,则事务完成后清理资源,就是解绑事务资源
if (status.isNewTransaction()) {
doCleanupAfterCompletion(status.getTransaction());
}
// 恢复被挂起的事务
if (status.getSuspendedResources() != null) {
if (status.isDebug()) {
logger.debug("Resuming suspended transaction after completion of inner transaction");
}
Object transaction = (status.hasTransaction() ? status.getTransaction() : null);
resume(transaction, (SuspendedResourcesHolder) status.getSuspendedResources());
}
}
如果是新事务,则事务完成后清理资源,解绑事务资源
@Override
protected void doCleanupAfterCompletion(Object transaction) {
DataSourceTransactionObject txObject = (DataSourceTransactionObject) transaction;
// 当前线程解绑连接
if (txObject.isNewConnectionHolder()) {
TransactionSynchronizationManager.unbindResource(obtainDataSource());
}
// 重置连接
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);
}
// 清理事务对象中的连接
txObject.getConnectionHolder().clear();
}
如果有挂起的事务,还需要对其恢复
protected final void resume(@Nullable Object transaction, @Nullable SuspendedResourcesHolder resourcesHolder)
throws TransactionException {
if (resourcesHolder != null) {
// 被挂起的事务资源
Object suspendedResources = resourcesHolder.suspendedResources;
if (suspendedResources != null) {
// 恢复事务,重新将线程与挂起的事务绑定
doResume(transaction, suspendedResources);
}
// 恢复事务同步
List<TransactionSynchronization> suspendedSynchronizations = resourcesHolder.suspendedSynchronizations;
if (suspendedSynchronizations != null) {
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);
}
5.4、不管事务执行结果如何,最终都要清除事务信息,恢复旧的事务信息
protected void cleanupTransactionInfo(@Nullable TransactionInfo txInfo) {
if (txInfo != null) {
txInfo.restoreThreadLocalStatus();
}
}
将旧的事务信息重新绑定到线程
private void restoreThreadLocalStatus() {
// 将事务信息重置到之前的状态
// Will be null if none was set.
transactionInfoHolder.set(this.oldTransactionInfo);
}
提交事务
5.5、提交事务
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;
// 如果被标记为仅回滚,则回滚,不会提交,
// 默认是false,除非开发者手动修改
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;
// 准备提交,在beforeCommit同步回调发生之前执行,交给开发者实现
prepareForCommit(status);
// 触发 beforeCommit 回调
triggerBeforeCommit(status);
// 触发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();
// 由具体的事务管理器提交
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 {
triggerAfterCompletion(status, TransactionSynchronization.STATUS_COMMITTED);
}
}
finally {
//清除TransactionSynchronizationManager的ThreadLocal绑定的数据。
//解除Thread绑定的resources资源。
//将Commit设置为自动提交。
//清理ConnectionHolder资源。
// 如果有挂起的事务,还要恢复挂起的事务,将挂起的事务重新绑定到当前线程
cleanupAfterCompletion(status);
}
}
● status.hasSavepoint()如果status有savePoint,说明此时的事务是嵌套事务NESTED,这个事务外面还有事务,这里不提交,只是释放保存点。这里也可以看出来NESTED的传播行为了。
● status.isNewTransaction()如果是新的事务,才会提交!!,这里如果是子事务,只有PROPAGATION_NESTED状态才会走到这里提交,也说明了此状态子事务提交和外层事务是隔离的。
● 如果是子事务,PROPAGATION_SUPPORTS 或 PROPAGATION_REQUIRED或PROPAGATION_MANDATORY这几种状态是旧事物,提交的时候将什么都不做,因为他们是运行在外层事务当中,如果子事务没有回滚,将由外层事务一次性提交。
接下来就是真正的提交事务了
@Override
protected void doCommit(DefaultTransactionStatus status) {
DataSourceTransactionObject txObject = (DataSourceTransactionObject) status.getTransaction();
// 获取事务中的连接
Connection con = txObject.getConnectionHolder().getConnection();
if (status.isDebug()) {
logger.debug("Committing JDBC transaction on Connection [" + con + "]");
}
try {
// 最终就是调用Connection的commit方法提交
con.commit();
}
catch (SQLException ex) {
throw new TransactionSystemException("Could not commit JDBC transaction", ex);
}
}
最后不管事务如何提交,最终都要调用cleanupAfterCompletion方法执行事务提交完成后的清理工作
private void cleanupAfterCompletion(DefaultTransactionStatus status) {
// 设置事务状态中的completed为true,表示事务完成
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());
}
}
如果是新事务,则事务完成后清理资源
@Override
protected void doCleanupAfterCompletion(Object transaction) {
DataSourceTransactionObject txObject = (DataSourceTransactionObject) transaction;
// Remove the connection holder from the thread, if exposed.
if (txObject.isNewConnectionHolder()) {
// 将连接与当前线程解绑
TransactionSynchronizationManager.unbindResource(obtainDataSource());
}
// 重置 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);
}
// 清除事务对象中的连接
txObject.getConnectionHolder().clear();
}