Spring源码解读(三)事务

一、spring事务简介

spring中有两种事务实现方式:

1)编程式事务
使用TransactionTemplate,实现更加细粒度的事务控制。

2)声明式事务
使用@Transactional,无代码侵入的事务使用方式。通过AOP实现,本质是在方法前后进行拦截,简单描述就是在方法开始前开启事务,结束后进行提交或者回滚。

二、编程式事务TransactionTemplate

下面看下类图:

image.png

如上图所示,发现其实现了TransactionOperrations和InitializingBean两个接口,继承自DefaultTransactionDefinition。分别看下都是干嘛的。

TransactionOperations内部是执行事务回调的方法,分别提供有返回值和没有返回值的两个方法。

image.png

InitializingBean是spring在bean初始化时预留的接口,专门用来在bean属性加载完成后用来执行的方法。

下面我们看看TransactionTemplate分别实现的这两个接口的哪些方法:

    @Override
    public void afterPropertiesSet() {
        //事务管理器是否为空
        if (this.transactionManager == null) {
            throw new IllegalArgumentException("Property 'transactionManager' is required");
        }
    }


    @Override
    @Nullable
    public <T> T execute(TransactionCallback<T> action) throws TransactionException {
        Assert.state(this.transactionManager != null, "No PlatformTransactionManager set");
        //内部封装的事务管理器
        if (this.transactionManager instanceof CallbackPreferringPlatformTransactionManager) {
            return ((CallbackPreferringPlatformTransactionManager) this.transactionManager).execute(this, action);
        }
        else {
            //手动获取事务,执行方法,提交事务管理器
            //1、获取事务
            TransactionStatus status = this.transactionManager.getTransaction(this);
            T result;
            try {
                //2、执行业务逻辑
                result = action.doInTransaction(status);
            }
            catch (RuntimeException | Error ex) {
                // 应用运行时异常-》回滚
                rollbackOnException(status, ex);
                throw ex;
            }
            catch (Throwable ex) {
                // 未知异常-》回滚
                rollbackOnException(status, ex);
                throw new UndeclaredThrowableException(ex, "TransactionCallback threw undeclared checked exception");
            }
            //、事务提交
            this.transactionManager.commit(status);
            return result;
        }
    }

三、声明式事务@Transactional

声明式事务的核心就是TransactionInterceptor

image.png

如上图所示,事务拦截器的拦截功能就是依靠实现了MethodInterceptor接口,这个是spring的方法拦截器。一个函数式接口,只有一个invoke方法。

@FunctionalInterface
public interface MethodInterceptor extends Interceptor {

    /**
     * Implement this method to perform extra treatments before and
     * after the invocation. Polite implementations would certainly
     * like to invoke {@link Joinpoint#proceed()}.
     * @param invocation the method invocation joinpoint
     * @return the result of the call to {@link Joinpoint#proceed()};
     * might be intercepted by the interceptor
     * @throws Throwable if the interceptors or the target object
     * throws an exception
     */
    @Nullable
    Object invoke(@Nonnull MethodInvocation invocation) throws Throwable;

}

看下其方法的实现:

    @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);
        
        // 调用TransactionAspectSupport的invokeWithinTransaction方法
        return invokeWithinTransaction(invocation.getMethod(), targetClass, invocation::proceed);
    }

下面主要关注invokeWithinTransaction方法,只注释主要的方法:

    @Nullable
    protected Object invokeWithinTransaction(Method method, @Nullable Class<?> targetClass,
            final InvocationCallback invocation) throws Throwable {

        // 如果事务属性为空,则该方法是非事务性的。
        TransactionAttributeSource tas = getTransactionAttributeSource();
        final TransactionAttribute txAttr = (tas != null ? tas.getTransactionAttribute(method, targetClass) : null);
        final TransactionManager tm = determineTransactionManager(txAttr);

        if (this.reactiveAdapterRegistry != null && tm instanceof ReactiveTransactionManager) {
            ReactiveTransactionSupport txSupport = this.transactionSupportCache.computeIfAbsent(method, key -> {
                if (KotlinDetector.isKotlinType(method.getDeclaringClass()) && KotlinDelegate.isSuspend(method)) {
                    throw new TransactionUsageException(
                            "Unsupported annotated transaction on suspending function detected: " + method +
                            ". Use TransactionalOperator.transactional extensions instead.");
                }
                ReactiveAdapter adapter = this.reactiveAdapterRegistry.getAdapter(method.getReturnType());
                if (adapter == null) {
                    throw new IllegalStateException("Cannot apply reactive transaction to non-reactive return type: " +
                            method.getReturnType());
                }
                return new ReactiveTransactionSupport(adapter);
            });
            return txSupport.invokeWithinTransaction(
                    method, targetClass, invocation, txAttr, (ReactiveTransactionManager) tm);
        }

        PlatformTransactionManager ptm = asPlatformTransactionManager(tm);
        final String joinpointIdentification = methodIdentification(method, targetClass, txAttr);
        // 声明式事务
        if (txAttr == null || !(ptm instanceof CallbackPreferringPlatformTransactionManager)) {
            // 使用 getTransaction 和 commit/rollback 调用进行标准事务划分。
            TransactionInfo txInfo = createTransactionIfNecessary(ptm, txAttr, joinpointIdentification);

            Object retVal;
            try {
                // 业务代码
                retVal = invocation.proceedWithInvocation();
            }
            catch (Throwable ex) {
                // 捕获异常,回滚或提交事务
                completeTransactionAfterThrowing(txInfo, ex);
                throw ex;
            }
            finally {
                //清空缓存的事务信心,并设置当前线程的事务信息为老的,即首次进入方法获取的事务
                cleanupTransactionInfo(txInfo);
            }

            if (retVal != null && vavrPresent && VavrDelegate.isVavrTry(retVal)) {
                // Set rollback-only in case of Vavr failure matching our rollback rules...
                TransactionStatus status = txInfo.getTransactionStatus();
                if (status != null && txAttr != null) {
                    retVal = VavrDelegate.evaluateTryFailure(retVal, txAttr, status);
                }
            }
            // 返回结果之前,进行事务提交
            commitTransactionAfterReturning(txInfo);
            return retVal;
        }
        //编程式事务
        else {
            Object result;
            final ThrowableHolder throwableHolder = new ThrowableHolder();

            // It's a CallbackPreferringPlatformTransactionManager: pass a TransactionCallback in.
            try {
                result = ((CallbackPreferringPlatformTransactionManager) ptm).execute(txAttr, status -> {
                    TransactionInfo txInfo = prepareTransactionInfo(ptm, txAttr, joinpointIdentification, status);
                    try {
                        Object retVal = invocation.proceedWithInvocation();
                        if (retVal != null && vavrPresent && VavrDelegate.isVavrTry(retVal)) {
                            // Set rollback-only in case of Vavr failure matching our rollback rules...
                            retVal = VavrDelegate.evaluateTryFailure(retVal, txAttr, status);
                        }
                        return retVal;
                    }
                    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);
                    }
                });
            }
            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;
            }

            // Check result state: It might indicate a Throwable to rethrow.
            if (throwableHolder.throwable != null) {
                throw throwableHolder.throwable;
            }
            return result;
        }
    }

3.1 createTransactionIfNecessary

    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) {
                // 获取事务状态
                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);
    }

prepareTransactionInfo

    protected TransactionInfo prepareTransactionInfo(@Nullable PlatformTransactionManager tm,
            @Nullable TransactionAttribute txAttr, String joinpointIdentification,
            @Nullable TransactionStatus status) {

        // 创建一个事务
        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.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.");
            }
        }

        // 将事务绑定到线程
        txInfo.bindToThread();
        return txInfo;
    }

bindToThread

        private void bindToThread() {
            // 获取当前事务信息并保存为旧的,以便日后进行恢复
            this.oldTransactionInfo = transactionInfoHolder.get();
            // 将当前事务绑定到当前持有者,transactionInfoHolder是一个ThreadLocal
            transactionInfoHolder.set(this);
        }

3.2 invocation.proceedWithInvocation() 回调业务代码

    @FunctionalInterface
    protected interface InvocationCallback {

        @Nullable
        Object proceedWithInvocation() throws Throwable;
    }

上面的接口实现其实是下面的方法,最终实现类是ReflectiveMethodInvocation:

image.png
image.png

如上图,ReflectiveMethodInvocation类实现了ProxyMethodInvocation接口,但是ProxyMethodInvocation继承了3层接口ProxyMethodInvocation -> MethodInvocation -> Invocation -> Joinpoint

Joinpoint:连接点接口,定义了执行接口:Object proceed() throws Throwable;
执行当前连接点,并跳到拦截器链上的下一个拦截器。

Invocation:调用接口,继承自Joinpoint,定义了获取参数接口: Object[] getArguments();
是一个带参数的、可被拦截器拦截的连接点。

MethodInvocation:方法调用接口,继承自Invocation,定义了获取方法接口:Method getMethod();
是一个带参数的可被拦截的连接点方法。

ProxyMethodInvocation:代理方法调用接口,继承自MethodInvocation,定义了获取代理对象接口:Object getProxy();
是一个由代理类执行的方法调用连接点方法。

ReflectiveMethodInvocation:实现了ProxyMethodInvocation接口,自然就实现了父类接口的的所有接口。
获取代理类,获取方法,获取参数,用代理类执行这个方法并且自动跳到下一个连接点

**proceed() **

    @Override
    @Nullable
    public Object proceed() throws Throwable {
        // 我们从 -1 的索引开始并提前增加。
        if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
            return invokeJoinpoint();
        }

        Object interceptorOrInterceptionAdvice =
                this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
        if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) {
            // 这里进行动态方法匹配校验,静态的方法匹配早已经校验过了
            InterceptorAndDynamicMethodMatcher dm =
                    (InterceptorAndDynamicMethodMatcher) interceptorOrInterceptionAdvice;
            Class<?> targetClass = (this.targetClass != null ? this.targetClass : this.method.getDeclaringClass());
            if (dm.methodMatcher.matches(this.method, targetClass, this.arguments)) {
                return dm.interceptor.invoke(this);
            }
            else {
                // 动态匹配失败,跳过当前拦截,进入下一个拦截器
                return proceed();
            }
        }
        else {
            // 它是一个拦截器,所以我们只需调用它:在构造这个对象之前,切入点将被静态计算
            // 这就是回调我们业务方法
            return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
        }
    }

3.3 completeTransactionAfterThrowing方法

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);
            }
            if (txInfo.transactionAttribute != null && txInfo.transactionAttribute.rollbackOn(ex)) {
                try {
                    // PlatformTransactionManager的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 {
                // 我们不会回滚这个异常
                // 如果 TransactionStatus.isRollbackOnly() 为真,仍将回滚
                try {
                    // PlatformTransactionManager的commit方法
                    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;
                }
            }
        }
    }

其实无论是声明式事务还是编程式事务,都是走的PlatformTransactionManager的getTranscation(),commit(),rockback()。

四、事务的核心源码

基于前面的简单分析,我们能够得出结论,PlatformTransactionManager就是整个spring事务的核心接口:

public interface PlatformTransactionManager extends TransactionManager {

        /**
         * 根据指定的传播行为,返回当前活动的事务或创建一个新事务。
         * 请注意,隔离级别或超时等参数仅适用于新事务,因此在参与活动事务时会被忽略。
         * 此外,并非每个事务管理器都支持所有事务定义设置:当遇到不支持的设置时,正确的事务管理器实现应该抛出异常。
         * 上述规则的一个例外是只读标志,如果不支持显式只读模式,则应忽略该标志。 本质上,只读标志只是潜在优化的提示。
     */
    TransactionStatus getTransaction(@Nullable TransactionDefinition definition)
            throws TransactionException;

        /**
         * 提交给定的事务根据其状态。 
         * 如果事务以编程方式标记为仅回滚,则执行回滚。
         * 如果事务不是新事务,则省略提交以正确参与周围的事务。 
         * 如果先前的事务已暂停以便能够创建新事务,则在提交新事务后恢复先前的事务。
         * 注意,当提交调用完成时,无论是正常还是抛出异常,都必须完全完成并清理事务
        */
    void commit(TransactionStatus status) throws TransactionException;

        /**
         * 执行给定事务的回滚。
         * 如果事务不是新事务,只需将其设置为仅回滚,以便正确参与周围的事务。 
         * 如果先前的事务已暂停以能够创建新事务,则在回滚新事务后恢复先前的事务。
         * 如果提交引发异常,则不要在事务上调用回滚。 
         * 即使在提交异常的情况下,事务也将在提交返回时已经完成并清理。 
         * 因此,提交失败后的回滚调用将导致 IllegalTransactionStateException
         */
    void rollback(TransactionStatus status) throws TransactionException;

4.1 getTransaction

大概的调用流程如下:


spring事务-getTransaction.png

代码如下:

    /**
     * This implementation handles propagation behavior. Delegates to
     * {@code doGetTransaction}, {@code isExistingTransaction}
     * and {@code doBegin}.
     * 此实现处理传播行为。 委托doGetTransaction 、 isExistingTransaction和doBegin
     * @see #doGetTransaction
     * @see #isExistingTransaction
     * @see #doBegin
     */
    @Override
    public final TransactionStatus getTransaction(@Nullable TransactionDefinition definition)
            throws TransactionException {

        // 如果没有给出事务定义,则使用默认值。
        TransactionDefinition def = (definition != null ? definition : TransactionDefinition.withDefaults());

        // DataSourceTransactionManager实现doGetTransaction方法,获取事务
        Object transaction = doGetTransaction();
        boolean debugEnabled = logger.isDebugEnabled();

        // 找到事务
        if (isExistingTransaction(transaction)) {
            // 找到现有事务 -> 检查传播行为以了解行为方式
            return handleExistingTransaction(def, transaction, debugEnabled);
        }

        // Check definition settings for new transaction.
        if (def.getTimeout() < TransactionDefinition.TIMEOUT_DEFAULT) {
            throw new InvalidTimeoutException("Invalid transaction timeout", def.getTimeout());
        }

        // 没找到现有事务 -> 检查传播行为以了解行为方式
        if (def.getPropagationBehavior() == TransactionDefinition.PROPAGATION_MANDATORY) {
            throw new IllegalTransactionStateException(
                    "No existing transaction found for transaction marked with propagation 'mandatory'");
        }
        //如果事务传播机制是以下三种:required,requires_new,nested,则新建事务
        else if (def.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRED ||
                def.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRES_NEW ||
                def.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NESTED) {
            SuspendedResourcesHolder suspendedResources = suspend(null);
            if (debugEnabled) {
                logger.debug("Creating new transaction with name [" + def.getName() + "]: " + def);
            }
            try {
                //开启一个事务
                return startTransaction(def, transaction, debugEnabled, suspendedResources);
            }
            catch (RuntimeException | Error ex) {
                resume(null, suspendedResources);
                throw ex;
            }
        }
        else {
            // 当前不存在事务,且传播机制=PROPAGATION_SUPPORTS/PROPAGATION_NOT_SUPPORTED/PROPAGATION_NEVER,这三种情况
            if (def.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT && logger.isWarnEnabled()) {
                logger.warn("Custom isolation level specified but no actual transaction initiated; " +
                        "isolation level will effectively be ignored: " + def);
            }
            boolean newSynchronization = (getTransactionSynchronization() == SYNCHRONIZATION_ALWAYS);
            return prepareTransactionStatus(def, null, true, newSynchronization, debugEnabled, null);
        }
    }

doGetTransaction:

    @Override
    protected Object doGetTransaction() {
        // 创建一个数据源事务管理对象
        DataSourceTransactionObject txObject = new DataSourceTransactionObject();
        // 设置是否允许嵌套事务,默认是false
        txObject.setSavepointAllowed(isNestedTransactionAllowed());
        // 获取jdbc连接
        ConnectionHolder conHolder =
                (ConnectionHolder) TransactionSynchronizationManager.getResource(obtainDataSource());
        txObject.setConnectionHolder(conHolder, false);
        return txObject;
    }

isExistingTransaction:

    @Override
    protected boolean isExistingTransaction(Object transaction) {
        DataSourceTransactionObject txObject = (DataSourceTransactionObject) transaction;
        //是否持有链接 和 是否存在事务
        return (txObject.hasConnectionHolder() && txObject.getConnectionHolder().isTransactionActive());
    }

startTransaction

    /**
     * Start a new transaction.
     */
    private TransactionStatus startTransaction(TransactionDefinition definition, Object transaction,
            boolean debugEnabled, @Nullable SuspendedResourcesHolder suspendedResources) {

        // 默认不开启事务同步
        boolean newSynchronization = (getTransactionSynchronization() != SYNCHRONIZATION_NEVER);
        // 根据给定参数创建一个事务
        DefaultTransactionStatus status = newTransactionStatus(
                definition, transaction, true, newSynchronization, debugEnabled, suspendedResources);
        // 开始一个新事务
        doBegin(transaction, definition);
        // 设置事务的名称,只读、隔离级别等等
        prepareSynchronization(status, definition);
        return status;
    }

doBegin

    @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");
                }
                // 设置数据连接
                txObject.setConnectionHolder(new ConnectionHolder(newCon), true);
            }

            // 开启事务同步
            txObject.getConnectionHolder().setSynchronizedWithTransaction(true);
            // 获取connection连接
            con = txObject.getConnectionHolder().getConnection();

            // 获取事务隔离级别
            Integer previousIsolationLevel = DataSourceUtils.prepareConnectionForTransaction(con, definition);
            // 设置事务隔离级别
            txObject.setPreviousIsolationLevel(previousIsolationLevel);
            txObject.setReadOnly(definition.isReadOnly());

            // 如有必要,切换到手动提交。这在某些 JDBC 驱动程序中非常昂贵
            // 所以我们不想做不必要的事情(例如,如果我们已经明确配置连接池来设置它)
            if (con.getAutoCommit()) {
                txObject.setMustRestoreAutoCommit(true);
                if (logger.isDebugEnabled()) {
                    logger.debug("Switching JDBC Connection [" + con + "] to manual commit");
                }
                // 关闭自动提交
                con.setAutoCommit(false);
            }

            prepareTransactionalConnection(con, definition);
            //设置此持有者是代表活动的、由 JDBC 管理的事务。
            txObject.getConnectionHolder().setTransactionActive(true);

            int timeout = determineTimeout(definition);
            if (timeout != TransactionDefinition.TIMEOUT_DEFAULT) {
                txObject.getConnectionHolder().setTimeoutInSeconds(timeout);
            }

            // 将连接绑定到线程上
            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);
        }
    }

到此为止上面一连串的流程都是基于事务的传播机制是required,我们除此之外还必须要明白requires_new和nested的过程。

在getTransaction()方法中,由于首次创建,三种方式都是一样的流程。当事务方法内部的方法仍然使用事务的时候,存在三种不同的情况,主要看getTransaction中下面的方法:handleExistingTransaction(),这个方法我们主要关注required,requires_nes,nested:

requires_new

        //如果事务时requires_new
        if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRES_NEW) {
            if (debugEnabled) {
                logger.debug("Suspending current transaction, creating new transaction with name [" +
                        definition.getName() + "]");
            }
            //暂停当前的事务
            SuspendedResourcesHolder suspendedResources = suspend(transaction);
            try {
                //创建新事务
                return startTransaction(definition, transaction, debugEnabled, suspendedResources);
            }
            catch (RuntimeException | Error beginEx) {
                resumeAfterBeginException(transaction, suspendedResources, beginEx);
                throw beginEx;
            }
        }

suspend方法:

    @Nullable
    protected final SuspendedResourcesHolder suspend(@Nullable Object transaction) throws TransactionException {
        //存在同步
        if (TransactionSynchronizationManager.isSynchronizationActive()) {
            List<TransactionSynchronization> suspendedSynchronizations = doSuspendSynchronization();
            try {
                Object suspendedResources = null;
                if (transaction != null) {
                    //事务不为空,挂起事务
                    suspendedResources = doSuspend(transaction);
                }
                //获取当前事务的属性
                String name = TransactionSynchronizationManager.getCurrentTransactionName();
                TransactionSynchronizationManager.setCurrentTransactionName(null);
                boolean readOnly = TransactionSynchronizationManager.isCurrentTransactionReadOnly();
                TransactionSynchronizationManager.setCurrentTransactionReadOnly(false);
                Integer isolationLevel = TransactionSynchronizationManager.getCurrentTransactionIsolationLevel();
                TransactionSynchronizationManager.setCurrentTransactionIsolationLevel(null);
                boolean wasActive = TransactionSynchronizationManager.isActualTransactionActive();
                TransactionSynchronizationManager.setActualTransactionActive(false);
                //创建一个挂起资源持有者
                return new SuspendedResourcesHolder(
                        suspendedResources, suspendedSynchronizations, name, readOnly, isolationLevel, wasActive);
            }
            catch (RuntimeException | Error ex) {
                // doSuspend failed - original transaction is still active...
                doResumeSynchronization(suspendedSynchronizations);
                throw ex;
            }
        }
        else if (transaction != null) {
            // 存在事务但是没有同步,挂起事务
            Object suspendedResources = doSuspend(transaction);
            // 返回挂起资源持有者
            return new SuspendedResourcesHolder(suspendedResources);
        }
        else {
            // 既没有事务,也没有同步
            return null;
        }
    }

doSuspend方法:

    @Override
    protected Object doSuspend(Object transaction) {
        //获取当前事务的数据库连接对象,并置为空
        DataSourceTransactionObject txObject = (DataSourceTransactionObject) transaction;
        txObject.setConnectionHolder(null);
        //从当前线程解除给定键的资源绑定。
        return TransactionSynchronizationManager.unbindResource(obtainDataSource());
    }

nested:

// 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走这
            if (useSavepointForNestedTransaction()) {
                // 在现有 Spring 管理的事务中创建保存点,
                // 通过 TransactionStatus 实现的 SavepointManager API。
                // 通常使用 JDBC 3.0 保存点。从不激活 Spring 同步。
                DefaultTransactionStatus status =
                        prepareTransactionStatus(definition, transaction, false, false, debugEnabled, null);
                //创建一个事务保存点
                status.createAndHoldSavepoint();
                return status;
            }
            else {
                //JTA从这走,开启一个新事务
                return startTransaction(definition, transaction, debugEnabled, null);
            }
        }

在handleExistingTransaction()存在每种传播机制的判断,不满足的会走最后一行代码:

        // 不符合上面的传播行为,所以走默认的,包含required
        // 关注第三个参数,newTransaction:false,不创建新事务
        return prepareTransactionStatus(definition, transaction, false, newSynchronization, debugEnabled, null);

4.2 commit

这里关注invokeWithinTransaction中的commitTransactionAfterReturning方法:

    protected void commitTransactionAfterReturning(@Nullable TransactionInfo txInfo) {
        // 存在事务就提交,否则什么都不做
        if (txInfo != null && txInfo.getTransactionStatus() != null) {
            if (logger.isTraceEnabled()) {
                logger.trace("Completing transaction for [" + txInfo.getJoinpointIdentification() + "]");
            }
            // 提交
            txInfo.getTransactionManager().commit(txInfo.getTransactionStatus());
        }
    }
    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);
    }

接下来只关注提交:processCommit(defStatus);

    private void processCommit(DefaultTransactionStatus status) throws TransactionException {
        try {
            boolean beforeCompletionInvoked = false;

            try {
                boolean unexpectedRollback = false;
                //三个前置操作
                // 没有实现
                prepareForCommit(status);
                // 提交之前回调
                triggerBeforeCommit(status);
                // 完成前回调
                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();
                }

                // 抛出 UnexpectedRollbackException 如果我们有一个全局仅回滚
                //标记但仍然没有从提交中获得相应的异常,手动抛出
                if (unexpectedRollback) {
                    throw new UnexpectedRollbackException(
                            "Transaction silently rolled back because it has been marked as rollback-only");
                }
            }
            catch (UnexpectedRollbackException ex) {
                // 触发完成后,同步状态设置为回滚
                triggerAfterCompletion(status, TransactionSynchronization.STATUS_ROLLED_BACK);
                throw ex;
            }
            catch (TransactionException ex) {
                // 提交失败则回滚
                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;
            }
            try {
                // 触发后置回调
                triggerAfterCommit(status);
            }
            finally {
                // 事务状态设置为已提交
                triggerAfterCompletion(status, TransactionSynchronization.STATUS_COMMITTED);
            }

        }
        finally {
            // 完成后处理事务状态
            cleanupAfterCompletion(status);
        }
    }

4.3 rollback

前面多次出现completeTransactionAfterThrowing方法,我们进入其内存看看毁掉方法的实现:

// PlatformTransactionManager的rollback方法
txInfo.getTransactionManager().rollback(txInfo.getTransactionStatus());

AbstractPlatformTransactionManager实现回调

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

processRollback:

    private void processRollback(DefaultTransactionStatus status, boolean unexpected) {
        try {
            // 默认false
            boolean unexpectedRollback = unexpected;

            try {
                //触发前置回调
                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");
                    }
                    //回滚
                    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;
            }

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

4.4 cleanupAfterCompletion

这个方法无论是提交还是回滚,都是最后一步需要做的,我们看下其源码:

    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(), txObject.isReadOnly());
        } 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();
    }

-----------结束:源码很枯燥,文章写的一般,感谢大家支持--------------

@Transactional声明式事务,有什么短板?

不能在内部使用远程服务调用,当网络发生超时,会持续占用数据库连接池,不被释放,持续侵占连接池资源。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,117评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,963评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 107,897评论 0 240
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,805评论 0 203
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,208评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,535评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,797评论 2 311
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,493评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,215评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,477评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,988评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,325评论 2 252
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,971评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,055评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,807评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,544评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,455评论 2 266