十八、spring 事務(wù)之事務(wù)執(zhí)行流程

接上一節(jié)十七、spring事務(wù)之簡單使用和原理。在spring aop中我們講到spring會把Adivsor中的Advice轉(zhuǎn)換成攔截器鏈,然后去調(diào)用。在上節(jié)中spring事務(wù)創(chuàng)建了一個(gè)BeanFactoryTransactionAttributeSourceAdvisor,并把TransactionInterceptor注入進(jìn)去,而TransactionInterceptor實(shí)現(xiàn)了Advice接口。所以這節(jié)分析TransactionInterceptor是如何管理事務(wù)的。

TransactionInterceptor

由類圖看出,TransactionInterceptor實(shí)現(xiàn)了MethodInterceptor接口,那么邏輯處理就會放在invoke方法中。

@Override
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...
    //調(diào)用父類的invokeWithinTransaction方法
    return invokeWithinTransaction(invocation.getMethod(), targetClass, new InvocationCallback() {
        @Override
        public Object proceedWithInvocation() throws Throwable {
            //執(zhí)行下一個(gè)調(diào)用鏈
            return invocation.proceed(); 
        }
    });
}

invoke方法把實(shí)現(xiàn)邏輯交給父類的invokeWithinTransaction,并利用回調(diào)的方式執(zhí)行下一個(gè)調(diào)用鏈。invokeWithinTransaction的實(shí)現(xiàn)邏輯如下,代碼粘貼最常用的部分:

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

    // If the transaction attribute is null, the method is non-transactional.
    //1. 獲取對應(yīng)事務(wù)屬性
    final TransactionAttribute txAttr = getTransactionAttributeSource().getTransactionAttribute(method, targetClass);
    //2. 獲取TransactionManager
    final PlatformTransactionManager tm = determineTransactionManager(txAttr);
    final String joinpointIdentification = methodIdentification(method, targetClass, txAttr);

    if (txAttr == null || !(tm instanceof CallbackPreferringPlatformTransactionManager)) {
        // Standard transaction demarcation with getTransaction and commit/rollback calls.
        //3. 創(chuàng)建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.
            //回調(diào)執(zhí)行下一個(gè)調(diào)用鏈
            retVal = invocation.proceedWithInvocation();
        }
        catch (Throwable ex) {
            // target invocation exception
            //異?;貪L
            completeTransactionAfterThrowing(txInfo, ex);
            throw ex;
        }
        finally {
            //清除事務(wù)信息
            cleanupTransactionInfo(txInfo);
        }
        //提交事務(wù)
        commitTransactionAfterReturning(txInfo);
        return retVal;
    }
}

invokeWithinTransaction代碼邏輯非常清晰,這里不得不夸贊下spring的代碼寫的真好,見名知意、邏輯清晰。上面方法的邏輯如下:

  1. 獲取對應(yīng)事務(wù)屬性,也就是獲取@Transactional注解上的屬性
  2. 獲取TransactionManager,常用的如DataSourceTransactionManager事務(wù)管理
  3. 在目標(biāo)方法執(zhí)行前獲取事務(wù)并收集事務(wù)信息
  4. 回調(diào)執(zhí)行下一個(gè)調(diào)用鏈。
  5. 一旦出現(xiàn)異常,嘗試異常處理
  6. 提交事務(wù)前的事務(wù)信息清理。
  7. 提交事務(wù)。

我們按照流程分析:

獲取對應(yīng)事務(wù)屬性

final TransactionAttribute txAttr = getTransactionAttributeSource().getTransactionAttribute(method, targetClass);

getTransactionAttributeSource()獲得的對象是在ProxyTransactionManagementConfiguration創(chuàng)建bean時(shí)注入的AnnotationTransactionAttributeSource對象。 AnnotationTransactionAttributeSource中g(shù)etTransactionAttributeSource方法主要邏輯交給了computeTransactionAttribute方法,所以我們直接看computeTransactionAttribute代碼實(shí)現(xiàn)。

protected TransactionAttribute computeTransactionAttribute(Method method, Class<?> targetClass) {
    // Don't allow no-public methods as required.
    //1. allowPublicMethodsOnly()返回true,只能是公共方法
    if (allowPublicMethodsOnly() && !Modifier.isPublic(method.getModifiers())) {
        return null;
    }

    // Ignore CGLIB subclasses - introspect the actual user class.
    Class<?> userClass = ClassUtils.getUserClass(targetClass);
    // The method may be on an interface, but we need attributes from the target class.
    // If the target class is null, the method will be unchanged.
    //method代表接口中的方法、specificMethod代表實(shí)現(xiàn)類的方法
    Method specificMethod = ClassUtils.getMostSpecificMethod(method, userClass);
    // If we are dealing with method with generic parameters, find the original method.
    //處理泛型
    specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);

    // First try is the method in the target class.
    //查看方法中是否存在事務(wù)
    TransactionAttribute txAttr = findTransactionAttribute(specificMethod);
    if (txAttr != null) {
        return txAttr;
    }

    // Second try is the transaction attribute on the target class.
    //查看方法所在類是否存在事務(wù)聲明
    txAttr = findTransactionAttribute(specificMethod.getDeclaringClass());
    if (txAttr != null && ClassUtils.isUserLevelMethod(method)) {
        return txAttr;
    }

    //如果存在接口,則在接口中查找
    if (specificMethod != method) {
        // Fallback is to look at the original method.
        //查找接口方法
        txAttr = findTransactionAttribute(method);
        if (txAttr != null) {
            return txAttr;
        }
        // Last fallback is the class of the original method.
        //到接口類中尋找
        txAttr = findTransactionAttribute(method.getDeclaringClass());
        if (txAttr != null && ClassUtils.isUserLevelMethod(method)) {
            return txAttr;
        }
    }

    return null;
}

computeTransactionAttribute方法執(zhí)行的邏輯是:

  1. 判斷是不是只運(yùn)行公共方法,在AnnotationTransactionAttributeSource構(gòu)造方法中傳入true。若方法不是公共方法,則返回null。
  2. 得到具體的方法,method方法可能是接口方法或者泛型方法。
  3. 查看方法上是否存在事務(wù)
  4. 查看方法所在類上是否存在事務(wù)
  5. 查看接口的方法是否存在事務(wù),查看接口上是否存在事務(wù)。

所以如果一個(gè)方法上用了@Transactional,類上和接口上也用了,以方法上的為主,其次才是類,最后才到接口。findTransactionAttribute方法的細(xì)節(jié)這里就不再描述了。

獲取TransactionManager

determineTransactionManager方法邏輯:

protected PlatformTransactionManager determineTransactionManager(TransactionAttribute txAttr) {
    // Do not attempt to lookup tx manager if no tx attributes are set
    if (txAttr == null || this.beanFactory == null) {
        return getTransactionManager();
    }
    String qualifier = txAttr.getQualifier();
    if (StringUtils.hasText(qualifier)) {
        return determineQualifiedTransactionManager(qualifier);
    }
    else if (StringUtils.hasText(this.transactionManagerBeanName)) {
        return determineQualifiedTransactionManager(this.transactionManagerBeanName);
    }
    else {
        //常用的會走到這里
        PlatformTransactionManager defaultTransactionManager = getTransactionManager();
        if (defaultTransactionManager == null) {
            defaultTransactionManager = this.transactionManagerCache.get(DEFAULT_TRANSACTION_MANAGER_KEY);
            if (defaultTransactionManager == null) {
                //從beanFactory獲取PlatformTransactionManager類型的bean
                defaultTransactionManager = this.beanFactory.getBean(PlatformTransactionManager.class);
                this.transactionManagerCache.putIfAbsent(
                        DEFAULT_TRANSACTION_MANAGER_KEY, defaultTransactionManager);
            }
        }
        return defaultTransactionManager;
    }
}

determineTransactionManager方法常用的都是從beanFactory中獲取,數(shù)據(jù)源的方式通過下面方式注冊:

@Bean
public PlatformTransactionManager txManager() {
    return new DataSourceTransactionManager(dataSource());
}

未完,下節(jié)分解。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容