spring事務詳解(三)源碼詳解

系列目錄

spring事務詳解(一)初探事務html

spring事務詳解(二)簡單樣例正則表達式

spring事務詳解(三)源碼詳解spring

spring事務詳解(四)測試驗證sql

spring事務詳解(五)總結提升數據庫

1、引子

在Spring中,事務有兩種實現方式:編程

  1. 編程式事務管理 編程式事務管理使用TransactionTemplate可實現更細粒度的事務控制。
  2. 申明式事務管理 基於Spring AOP實現。其本質是對方法先後進行攔截,而後在目標方法開始以前建立或者加入一個事務,在執行完目標方法以後根據執行狀況提交或者回滾事務。

申明式事務管理不須要入侵代碼,經過@Transactional就能夠進行事務操做,更快捷並且簡單(尤爲是配合spring boot自動配置,能夠說是精簡至極!),且大部分業務均可以知足,推薦使用。緩存

其實無論是編程式事務仍是申明式事務,最終調用的底層核心代碼是一致的。本章分別從編程式、申明式入手,再進入核心源碼貫穿式講解。springboot

2、事務源碼

2.1 編程式事務TransactionTemplate

編程式事務,Spring已經給咱們提供好了模板類TransactionTemplate,能夠很方便的使用,以下圖:markdown

TransactionTemplate全路徑名是:org.springframework.transaction.support.TransactionTemplate。看包名也知道了這是spring對事務的模板類。(spring動不動就是各類Template...),看下類圖先:session

一看,喲西,實現了TransactionOperations、InitializingBean這2個接口(熟悉spring源碼的知道這個InitializingBean又是老套路),咱們來看下接口源碼以下:

 1 public interface TransactionOperations {  2  3 /**  4  * Execute the action specified by the given callback object within a transaction.  5  * <p>Allows for returning a result object created within the transaction, that is,  6  * a domain object or a collection of domain objects. A RuntimeException thrown  7  * by the callback is treated as a fatal exception that enforces a rollback.  8  * Such an exception gets propagated to the caller of the template.  9  * @param action the callback object that specifies the transactional action 10  * @return a result object returned by the callback, or {@code null} if none 11  * @throws TransactionException in case of initialization, rollback, or system errors 12  * @throws RuntimeException if thrown by the TransactionCallback 13 */ 14 <T> T execute(TransactionCallback<T> action) throws TransactionException; 15 16 } 17 18 public interface InitializingBean { 19 20 /** 21  * Invoked by a BeanFactory after it has set all bean properties supplied 22  * (and satisfied BeanFactoryAware and ApplicationContextAware). 23  * <p>This method allows the bean instance to perform initialization only 24  * possible when all bean properties have been set and to throw an 25  * exception in the event of misconfiguration. 26  * @throws Exception in the event of misconfiguration (such 27  * as failure to set an essential property) or if initialization fails. 28 */ 29 void afterPropertiesSet() throws Exception; 30 31 }

如上圖,TransactionOperations這個接口用來執行事務的回調方法,InitializingBean這個是典型的spring bean初始化流程中(飛機票:Spring IOC(四)總結昇華篇)的預留接口,專用用來在bean屬性加載完畢時執行的方法。

回到正題,TransactionTemplate的2個接口的impl方法作了什麼?

 1     @Override  2 public void afterPropertiesSet() {  3 if (this.transactionManager == null) {  4 throw new IllegalArgumentException("Property 'transactionManager' is required");  5  }  6  }  7  8  9  @Override 10 public <T> T execute(TransactionCallback<T> action) throws TransactionException {
       // 內部封裝好的事務管理器 11 if (this.transactionManager instanceof CallbackPreferringPlatformTransactionManager) { 12 return ((CallbackPreferringPlatformTransactionManager) this.transactionManager).execute(this, action); 13 }// 須要手動獲取事務,執行方法,提交事務的管理器 14 else {// 1.獲取事務狀態 15 TransactionStatus status = this.transactionManager.getTransaction(this); 16 T result; 17 try {// 2.執行業務邏輯 18 result = action.doInTransaction(status); 19 } 20 catch (RuntimeException ex) { 21 // 應用運行時異常 -> 回滾 22 rollbackOnException(status, ex); 23 throw ex; 24 } 25 catch (Error err) { 26 // Error異常 -> 回滾 27 rollbackOnException(status, err); 28 throw err; 29 } 30 catch (Throwable ex) { 31 // 未知異常 -> 回滾 32 rollbackOnException(status, ex); 33 throw new UndeclaredThrowableException(ex, "TransactionCallback threw undeclared checked exception"); 34 }// 3.事務提交 35 this.transactionManager.commit(status); 36 return result; 37 } 38 }

如上圖所示,實際上afterPropertiesSet只是校驗了事務管理器不爲空,execute()纔是核心方法,execute主要步驟:

1.getTransaction()獲取事務,源碼見3.3.1

2.doInTransaction()執行業務邏輯,這裏就是用戶自定義的業務代碼。若是是沒有返回值的,就是doInTransactionWithoutResult()。

3.commit()事務提交調用AbstractPlatformTransactionManager的commitrollbackOnException()異常回滾:調用AbstractPlatformTransactionManager的rollback()事務提交回滾,源碼見3.3.3

 

2.2 申明式事務@Transactional

1.AOP相關概念

申明式事務使用的是spring AOP,即面向切面編程。(什麼❓你不知道什麼是AOP...一句話歸納就是:把業務代碼中重複代碼作成一個切面,提取出來,並定義哪些方法須要執行這個切面。其它的自行百度吧...)AOP核心概念以下:

  • 通知(Advice):定義了切面(各處業務代碼中都須要的邏輯提煉成的一個切面)作什麼what+when什麼時候使用。例如:前置通知Before、後置通知After、返回通知After-returning、異常通知After-throwing、環繞通知Around.
  • 鏈接點(Joint point):程序執行過程當中可以插入切面的點,通常有多個。好比調用方式時、拋出異常時。
  • 切點(Pointcut):切點定義了鏈接點,切點包含多個鏈接點,即where哪裏使用通知.一般指定類+方法 或者 正則表達式來匹配 類和方法名稱。
  • 切面(Aspect):切面=通知+切點,即when+where+what什麼時候何地作什麼
  • 引入(Introduction):容許咱們向現有的類添加新方法或屬性。
  • 織入(Weaving):織入是把切面應用到目標對象並建立新的代理對象的過程。

2.申明式事務

申明式事務總體調用過程,能夠抽出2條線:

1.使用代理模式,生成代理加強類。

2.根據代理事務管理配置類,配置事務的織入,在業務方法先後進行環繞加強,增長一些事務的相關操做。例如獲取事務屬性、提交事務、回滾事務。

過程以下圖:

申明式事務使用@Transactional這種註解的方式,那麼咱們就從springboot 容器啓動時的自動配置載入(spring boot容器啓動詳解)開始看。在/META-INF/spring.factories中配置文件中查找,以下圖:

 

載入2個關於事務的自動配置類: 

org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration,
org.springframework.boot.autoconfigure.transaction.jta.JtaAutoConfiguration,

jta我們就不看了,看一下TransactionAutoConfiguration這個自動配置類:

 1 @Configuration
 2 @ConditionalOnClass(PlatformTransactionManager.class)
 3 @AutoConfigureAfter({ JtaAutoConfiguration.class, HibernateJpaAutoConfiguration.class,
 4         DataSourceTransactionManagerAutoConfiguration.class,
 5         Neo4jDataAutoConfiguration.class })
 6 @EnableConfigurationProperties(TransactionProperties.class)
 7 public class TransactionAutoConfiguration {
 8 
 9     @Bean
10     @ConditionalOnMissingBean
11     public TransactionManagerCustomizers platformTransactionManagerCustomizers(
12             ObjectProvider<List<PlatformTransactionManagerCustomizer<?>>> customizers) {
13         return new TransactionManagerCustomizers(customizers.getIfAvailable());
14     }
15 
16     @Configuration
17     @ConditionalOnSingleCandidate(PlatformTransactionManager.class)
18     public static class TransactionTemplateConfiguration {
19 
20         private final PlatformTransactionManager transactionManager;
21 
22         public TransactionTemplateConfiguration(
23                 PlatformTransactionManager transactionManager) {
24             this.transactionManager = transactionManager;
25         }
26 
27         @Bean
28         @ConditionalOnMissingBean 29         public TransactionTemplate transactionTemplate() {
30             return new TransactionTemplate(this.transactionManager);
31         }
32     }
33 
34     @Configuration
35     @ConditionalOnBean(PlatformTransactionManager.class)
36     @ConditionalOnMissingBean(AbstractTransactionManagementConfiguration.class)
37     public static class EnableTransactionManagementConfiguration {
38 
39         @Configuration
40         @EnableTransactionManagement(proxyTargetClass = false)
41         @ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "false", matchIfMissing = false)
42         public static class JdkDynamicAutoProxyConfiguration {
43 
44         }
45 
46         @Configuration
47         @EnableTransactionManagement(proxyTargetClass = true)
48         @ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "true", matchIfMissing = true)
49         public static class CglibAutoProxyConfiguration {
50 
51         }
52 
53     }
54 
55 }

TransactionAutoConfiguration這個類主要看:

1.2個類註解

@ConditionalOnClass(PlatformTransactionManager.class)即類路徑下包含PlatformTransactionManager這個類時這個自動配置生效,這個類是spring事務的核心包,確定引入了。

@AutoConfigureAfter({ JtaAutoConfiguration.class, HibernateJpaAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, Neo4jDataAutoConfiguration.class }),這個配置在括號中的4個配置類後才生效。

2. 2個內部類

TransactionTemplateConfiguration事務模板配置類

@ConditionalOnSingleCandidate(PlatformTransactionManager.class)當可以惟一肯定一個PlatformTransactionManager bean時才生效。

@ConditionalOnMissingBean若是沒有定義TransactionTemplate bean生成一個。

EnableTransactionManagementConfiguration開啓事務管理器配置類

@ConditionalOnBean(PlatformTransactionManager.class)當存在PlatformTransactionManager bean時生效。

@ConditionalOnMissingBean(AbstractTransactionManagementConfiguration.class)當沒有自定義抽象事務管理器配置類時才生效。(即用戶自定義抽象事務管理器配置類會優先,若是沒有,就用這個默認事務管理器配置類)

EnableTransactionManagementConfiguration支持2種代理方式:

  • 1.JdkDynamicAutoProxyConfiguration

@EnableTransactionManagement(proxyTargetClass = false),即proxyTargetClass = false表示是JDK動態代理支持的是:面向接口代理。

@ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "false", matchIfMissing = false),即spring.aop.proxy-target-class=false時生效,且沒有這個配置不生效。

  • 2.CglibAutoProxyConfiguration

@EnableTransactionManagement(proxyTargetClass = true),即proxyTargetClass = true標識Cglib代理支持的是子類繼承代理。
@ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "true", matchIfMissing = true),即spring.aop.proxy-target-class=true時生效,且沒有這個配置默認生效。

注意了,默認沒有配置,走的Cglib代理。說明@Transactional註解支持直接加在類上。

好吧,看了這麼多配置類,終於到了@EnableTransactionManagement這個註解了。

 1 @Target(ElementType.TYPE)
 2 @Retention(RetentionPolicy.RUNTIME)
 3 @Documented
 4 @Import(TransactionManagementConfigurationSelector.class)
 5 public @interface EnableTransactionManagement {
 6 
 7     //proxyTargetClass = false表示是JDK動態代理支持接口代理。true表示是Cglib代理支持子類繼承代理。
 8     boolean proxyTargetClass() default false;
 9 
10     //事務通知模式(切面織入方式),默認代理模式(同一個類中方法互相調用攔截器不會生效),能夠選擇加強型AspectJ
11     AdviceMode mode() default AdviceMode.PROXY;
12 
13     //鏈接點上有多個通知時,排序,默認最低。值越大優先級越低。
14     int order() default Ordered.LOWEST_PRECEDENCE;
15 
16 }

重點看類註解@Import(TransactionManagementConfigurationSelector.class)

TransactionManagementConfigurationSelector類圖以下:

如上圖所示,TransactionManagementConfigurationSelector繼承自AdviceModeImportSelector實現了ImportSelector接口。

 1 public class TransactionManagementConfigurationSelector extends AdviceModeImportSelector<EnableTransactionManagement> {
 2 
 3     /**
 4      * {@inheritDoc}
 5      * @return {@link ProxyTransactionManagementConfiguration} or
 6      * {@code AspectJTransactionManagementConfiguration} for {@code PROXY} and
 7      * {@code ASPECTJ} values of {@link EnableTransactionManagement#mode()}, respectively
 8      */
 9     @Override
10     protected String[] selectImports(AdviceMode adviceMode) {
11         switch (adviceMode) {
12             case PROXY:
13                 return new String[] {AutoProxyRegistrar.class.getName(), ProxyTransactionManagementConfiguration.class.getName()};
14             case ASPECTJ:
15                 return new String[] {TransactionManagementConfigUtils.TRANSACTION_ASPECT_CONFIGURATION_CLASS_NAME};
16             default:
17                 return null;
18         }
19     }
20 
21 }

如上圖,最終會執行selectImports方法導入須要加載的類,咱們只看proxy模式下,載入了AutoProxyRegistrar、ProxyTransactionManagementConfiguration2個類。

  • AutoProxyRegistrar:給容器中註冊一個 InfrastructureAdvisorAutoProxyCreator 組件;利用後置處理器機制在對象建立之後,包裝對象,返回一個代理對象(加強器),代理對象執行方法利用攔截器鏈進行調用;
  • ProxyTransactionManagementConfiguration:就是一個配置類,定義了事務加強器。

AutoProxyRegistrar

先看AutoProxyRegistrar實現了ImportBeanDefinitionRegistrar接口,複寫registerBeanDefinitions方法,源碼以下:

 1 public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
 2         boolean candidateFound = false;
 3         Set<String> annoTypes = importingClassMetadata.getAnnotationTypes();
 4         for (String annoType : annoTypes) {
 5             AnnotationAttributes candidate = AnnotationConfigUtils.attributesFor(importingClassMetadata, annoType);
 6             if (candidate == null) {
 7                 continue;
 8             }
 9             Object mode = candidate.get("mode");
10             Object proxyTargetClass = candidate.get("proxyTargetClass");
11             if (mode != null && proxyTargetClass != null && AdviceMode.class == mode.getClass() &&
12                     Boolean.class == proxyTargetClass.getClass()) {
13                 candidateFound = true;
14                 if (mode == AdviceMode.PROXY) {//代理模式
15                     AopConfigUtils.registerAutoProxyCreatorIfNecessary(registry);
16                     if ((Boolean) proxyTargetClass) {//若是是CGLOB子類代理模式
17                         AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry);
18                         return;
19                     }
20                 }
21             }
22         }
23         if (!candidateFound) {
24             String name = getClass().getSimpleName();
25             logger.warn(String.format("%s was imported but no annotations were found " +
26                     "having both 'mode' and 'proxyTargetClass' attributes of type " +
27                     "AdviceMode and boolean respectively. This means that auto proxy " +
28                     "creator registration and configuration may not have occurred as " +
29                     "intended, and components may not be proxied as expected. Check to " +
30                     "ensure that %s has been @Import'ed on the same class where these " +
31                     "annotations are declared; otherwise remove the import of %s " +
32                     "altogether.", name, name, name));
33         }
34     }

代理模式:AopConfigUtils.registerAutoProxyCreatorIfNecessary(registry);

最終調用的是:registerOrEscalateApcAsRequired(InfrastructureAdvisorAutoProxyCreator.class, registry, source);基礎構建加強自動代理構造器

 1 private static BeanDefinition registerOrEscalateApcAsRequired(Class<?> cls, BeanDefinitionRegistry registry, Object source) {
 2         Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
       //若是當前註冊器包含internalAutoProxyCreator
3 if (registry.containsBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME)) {//org.springframework.aop.config.internalAutoProxyCreator內部自動代理構造器 4 BeanDefinition apcDefinition = registry.getBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME); 5 if (!cls.getName().equals(apcDefinition.getBeanClassName())) {//若是當前類不是internalAutoProxyCreator 6 int currentPriority = findPriorityForClass(apcDefinition.getBeanClassName()); 7 int requiredPriority = findPriorityForClass(cls); 8 if (currentPriority < requiredPriority) {//若是下標大於已存在的內部自動代理構造器,index越小,優先級越高,InfrastructureAdvisorAutoProxyCreator index=0,requiredPriority最小,不進入 9 apcDefinition.setBeanClassName(cls.getName()); 10 } 11 } 12 return null;//直接返回 13 }//若是當前註冊器不包含internalAutoProxyCreator,則把當前類做爲根定義 14 RootBeanDefinition beanDefinition = new RootBeanDefinition(cls); 15 beanDefinition.setSource(source); 16 beanDefinition.getPropertyValues().add("order", Ordered.HIGHEST_PRECEDENCE);//優先級最高 17 beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); 18 registry.registerBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME, beanDefinition); 19 return beanDefinition; 20 }

如上圖,APC_PRIORITY_LIST列表以下圖:

 1 /**
 2      * Stores the auto proxy creator classes in escalation order.
 3      */
 4     private static final List<Class<?>> APC_PRIORITY_LIST = new ArrayList<Class<?>>();
 5 
 6     /**
 7      * 優先級上升list
 8      */
 9     static {
10         APC_PRIORITY_LIST.add(InfrastructureAdvisorAutoProxyCreator.class);
11         APC_PRIORITY_LIST.add(AspectJAwareAdvisorAutoProxyCreator.class);
12         APC_PRIORITY_LIST.add(AnnotationAwareAspectJAutoProxyCreator.class);
13     }

如上圖,因爲InfrastructureAdvisorAutoProxyCreator這個類在list中第一個index=0,requiredPriority最小,不進入,因此沒有重置beanClassName,啥都沒作,返回null.

那麼加強代理類什麼時候生成呢?

InfrastructureAdvisorAutoProxyCreator類圖以下:

如上圖所示,看2個核心方法:InstantiationAwareBeanPostProcessor接口的postProcessBeforeInstantiation實例化前+BeanPostProcessor接口的postProcessAfterInitialization初始化後。關於spring bean生命週期飛機票:Spring IOC(四)總結昇華篇

 1     @Override
 2     public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
 3         Object cacheKey = getCacheKey(beanClass, beanName);
 4 
 5         if (beanName == null || !this.targetSourcedBeans.contains(beanName)) {
 6             if (this.advisedBeans.containsKey(cacheKey)) {//若是已經存在直接返回
 7                 return null;
 8             }//是否基礎構件(基礎構建不須要代理):Advice、Pointcut、Advisor、AopInfrastructureBean這四類都算基礎構建
 9             if (isInfrastructureClass(beanClass) || shouldSkip(beanClass, beanName)) {
10                 this.advisedBeans.put(cacheKey, Boolean.FALSE);//添加進advisedBeans ConcurrentHashMap<k=Object,v=Boolean>標記是否須要加強實現,這裏基礎構建bean不須要代理,都置爲false,供後面postProcessAfterInitialization實例化後使用。
11                 return null;
12             }
13         }
14 
15         // TargetSource是spring aop預留給咱們用戶自定義實例化的接口,若是存在TargetSource就不會默認實例化,而是按照用戶自定義的方式實例化,我們沒有定義,不進入
18         if (beanName != null) {
19             TargetSource targetSource = getCustomTargetSource(beanClass, beanName);
20             if (targetSource != null) {
21                 this.targetSourcedBeans.add(beanName);
22                 Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(beanClass, beanName, targetSource);
23                 Object proxy = createProxy(beanClass, beanName, specificInterceptors, targetSource);
24                 this.proxyTypes.put(cacheKey, proxy.getClass());
25                 return proxy;
26             }
27         }
28 
29         return null;
30     }

經過追蹤,因爲InfrastructureAdvisorAutoProxyCreator是基礎構建類,

advisedBeans.put(cacheKey, Boolean.FALSE)

添加進advisedBeans ConcurrentHashMap<k=Object,v=Boolean>標記是否須要加強實現,這裏基礎構建bean不須要代理,都置爲false,供後面postProcessAfterInitialization實例化後使用。

咱們再看postProcessAfterInitialization源碼以下:

 1     @Override
 2     public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
 3         if (bean != null) {
 4             Object cacheKey = getCacheKey(bean.getClass(), beanName);
 5             if (!this.earlyProxyReferences.contains(cacheKey)) {
 6                 return wrapIfNecessary(bean, beanName, cacheKey);
 7             }
 8         }
 9         return bean;
10     }
11 
12     protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
       // 若是是用戶自定義獲取實例,不須要加強處理,直接返回
13 if (beanName != null && this.targetSourcedBeans.contains(beanName)) { 14 return bean; 15 }// 查詢map緩存,記過false,不須要加強直接返回 16 if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) { 17 return bean; 18 }// 判斷一遍springAOP基礎構建類,標記過false,不須要加強直接返回 19 if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) { 20 this.advisedBeans.put(cacheKey, Boolean.FALSE); 21 return bean; 22 } 23 24 // 獲取加強List<Advisor> advisors 25 Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
       // 若是存在加強
26 if (specificInterceptors != DO_NOT_PROXY) { 27 this.advisedBeans.put(cacheKey, Boolean.TRUE);// 標記加強爲TRUE,表示須要加強實現
         // 生成加強代理類
28 Object proxy = createProxy( 29 bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean)); 30 this.proxyTypes.put(cacheKey, proxy.getClass()); 31 return proxy; 32 } 33      // 若是不存在加強,標記false,做爲緩存,再次進入提升效率,第16行利用緩存先校驗 34 this.advisedBeans.put(cacheKey, Boolean.FALSE); 35 return bean; 36 }

下面看核心方法createProxy以下:

 1     protected Object createProxy(
 2             Class<?> beanClass, String beanName, Object[] specificInterceptors, TargetSource targetSource) {
 3      // 若是是ConfigurableListableBeanFactory接口(我們DefaultListableBeanFactory就是該接口的實現類)則,暴露目標類
 4         if (this.beanFactory instanceof ConfigurableListableBeanFactory) {
         //給beanFactory->beanDefinition定義一個屬性:k=AutoProxyUtils.originalTargetClass,v=須要被代理的bean class
5 AutoProxyUtils.exposeTargetClass((ConfigurableListableBeanFactory) this.beanFactory, beanName, beanClass); 6 } 7 8 ProxyFactory proxyFactory = new ProxyFactory(); 9 proxyFactory.copyFrom(this); 10      //若是不是代理目標類 11 if (!proxyFactory.isProxyTargetClass()) {//若是beanFactory定義了代理目標類(CGLIB) 12 if (shouldProxyTargetClass(beanClass, beanName)) { 13 proxyFactory.setProxyTargetClass(true);//代理工廠設置代理目標類 14 } 15 else {//不然設置代理接口(JDK) 16 evaluateProxyInterfaces(beanClass, proxyFactory); 17 } 18 } 19      //把攔截器包裝成加強(通知) 20 Advisor[] advisors = buildAdvisors(beanName, specificInterceptors); 21 proxyFactory.addAdvisors(advisors);//設置進代理工廠 22 proxyFactory.setTargetSource(targetSource); 23 customizeProxyFactory(proxyFactory);//空方法,留給子類拓展用,典型的spring的風格,喜歡到處留後路 24      //用於控制代理工廠是否還容許再次添加通知,默認爲false(表示不容許) 25 proxyFactory.setFrozen(this.freezeProxy); 26 if (advisorsPreFiltered()) {//默認false,上面已經前置過濾了匹配的加強Advisor 27 proxyFactory.setPreFiltered(true); 28 } 29 //代理工廠獲取代理對象的核心方法 30 return proxyFactory.getProxy(getProxyClassLoader()); 31 }

最終咱們生成的是CGLIB代理類.到此爲止咱們分析完了代理類的構造過程。

ProxyTransactionManagementConfiguration

下面來看ProxyTransactionManagementConfiguration

 1 @Configuration
 2 public class ProxyTransactionManagementConfiguration extends AbstractTransactionManagementConfiguration {
 3 
 4     @Bean(name = TransactionManagementConfigUtils.TRANSACTION_ADVISOR_BEAN_NAME)
 5     @Role(BeanDefinition.ROLE_INFRASTRUCTURE)//定義事務加強器
 6     public BeanFactoryTransactionAttributeSourceAdvisor transactionAdvisor() {
 7         BeanFactoryTransactionAttributeSourceAdvisor j = new BeanFactoryTransactionAttributeSourceAdvisor();
 8         advisor.setTransactionAttributeSource(transactionAttributeSource());
 9         advisor.setAdvice(transactionInterceptor());
10         advisor.setOrder(this.enableTx.<Integer>getNumber("order"));
11         return advisor;
12     }
13 
14     @Bean
15     @Role(BeanDefinition.ROLE_INFRASTRUCTURE)//定義基於註解的事務屬性資源
16     public TransactionAttributeSource transactionAttributeSource() {
17         return new AnnotationTransactionAttributeSource();
18     }
19 
20     @Bean
21     @Role(BeanDefinition.ROLE_INFRASTRUCTURE)//定義事務攔截器
22     public TransactionInterceptor transactionInterceptor() {
23         TransactionInterceptor interceptor = new TransactionInterceptor();
24         interceptor.setTransactionAttributeSource(transactionAttributeSource());
25         if (this.txManager != null) {
26             interceptor.setTransactionManager(this.txManager);
27         }
28         return interceptor;
29     }
30 
31 }

核心方法:transactionAdvisor()事務織入

定義了一個advisor,設置事務屬性、設置事務攔截器TransactionInterceptor、設置順序。核心就是事務攔截器TransactionInterceptor

TransactionInterceptor使用通用的spring事務基礎架構實現「聲明式事務」,繼承自TransactionAspectSupport類(該類包含與Spring的底層事務API的集成),實現了MethodInterceptor接口。spring類圖以下:

事務攔截器的攔截功能就是依靠實現了MethodInterceptor接口,熟悉spring的同窗確定很熟悉MethodInterceptor了,這個是spring的方法攔截器,主要看invoke方法:

 1 @Override
 2     public Object invoke(final MethodInvocation invocation) throws Throwable {
 3         // Work out the target class: may be {@code null}.
 4         // The TransactionAttributeSource should be passed the target class
 5         // as well as the method, which may be from an interface.
 6         Class<?> targetClass = (invocation.getThis() != null ? AopUtils.getTargetClass(invocation.getThis()) : null);
 7 
 8         // 調用TransactionAspectSupport的 invokeWithinTransaction方法
 9         return invokeWithinTransaction(invocation.getMethod(), targetClass, new InvocationCallback() {
10             @Override
11             public Object proceedWithInvocation() throws Throwable {
12                 return invocation.proceed();
13             }
14         });
15     }

如上圖TransactionInterceptor複寫MethodInterceptor接口的invoke方法,並在invoke方法中調用了父類TransactionAspectSupportinvokeWithinTransaction()方法,源碼以下:

 1 protected Object invokeWithinTransaction(Method method, Class<?> targetClass, final InvocationCallback invocation)
 2             throws Throwable {  
 3 
 4         // 若是transaction attribute爲空,該方法就是非事務(非編程式事務)
 5         final TransactionAttribute txAttr = getTransactionAttributeSource().getTransactionAttribute(method, targetClass);
 6         final PlatformTransactionManager tm = determineTransactionManager(txAttr);
 7         final String joinpointIdentification = methodIdentification(method, targetClass, txAttr);
 8      // 標準聲明式事務:若是事務屬性爲空 或者 非回調偏向的事務管理器
 9         if (txAttr == null || !(tm instanceof CallbackPreferringPlatformTransactionManager)) {
10             // Standard transaction demarcation with getTransaction and commit/rollback calls.
11             TransactionInfo txInfo = createTransactionIfNecessary(tm, txAttr, joinpointIdentification);
12             Object retVal = null;
13             try {
14                 // 這裏就是一個環繞加強,在這個proceed先後能夠本身定義加強實現
15                 // 方法執行
16                 retVal = invocation.proceedWithInvocation();
17             }
18             catch (Throwable ex) {
19                 // 根據事務定義的,該異常須要回滾就回滾,不然提交事務
20  completeTransactionAfterThrowing(txInfo, ex);
21                 throw ex;
22             }
23             finally {//清空當前事務信息,重置爲老的
24  cleanupTransactionInfo(txInfo);
25             }//返回結果以前提交事務
26  commitTransactionAfterReturning(txInfo);
27             return retVal;
28         }
29      // 編程式事務:(回調偏向)
30         else {
31             final ThrowableHolder throwableHolder = new ThrowableHolder();
32 
33             // It's a CallbackPreferringPlatformTransactionManager: pass a TransactionCallback in.
34             try {
35                 Object result = ((CallbackPreferringPlatformTransactionManager) tm).execute(txAttr,
36                         new TransactionCallback<Object>() {
37                             @Override
38                             public Object doInTransaction(TransactionStatus status) {
39                                 TransactionInfo txInfo = prepareTransactionInfo(tm, txAttr, joinpointIdentification, status);
40                                 try {
41                                     return invocation.proceedWithInvocation();
42                                 }
43                                 catch (Throwable ex) {// 若是該異常須要回滾
44                                     if (txAttr.rollbackOn(ex)) {
45                                         // 若是是運行時異常返回
46                                         if (ex instanceof RuntimeException) {
47                                             throw (RuntimeException) ex;
48                                         }// 若是是其它異常都拋ThrowableHolderException
49                                         else {
50                                             throw new ThrowableHolderException(ex);
51                                         }
52                                     }// 若是不須要回滾
53                                     else {
54                                         // 定義異常,最終就直接提交事務了
55                                         throwableHolder.throwable = ex;
56                                         return null;
57                                     }
58                                 }
59                                 finally {//清空當前事務信息,重置爲老的
60  cleanupTransactionInfo(txInfo);
61                                 }
62                             }
63                         });
64 
65                 // 上拋異常
66                 if (throwableHolder.throwable != null) {
67                     throw throwableHolder.throwable;
68                 }
69                 return result;
70             }
71             catch (ThrowableHolderException ex) {
72                 throw ex.getCause();
73             }
74             catch (TransactionSystemException ex2) {
75                 if (throwableHolder.throwable != null) {
76                     logger.error("Application exception overridden by commit exception", throwableHolder.throwable);
77                     ex2.initApplicationException(throwableHolder.throwable);
78                 }
79                 throw ex2;
80             }
81             catch (Throwable ex2) {
82                 if (throwableHolder.throwable != null) {
83                     logger.error("Application exception overridden by commit exception", throwableHolder.throwable);
84                 }
85                 throw ex2;
86             }
87         }
88     }

 如上圖,咱們主要看第一個分支,申明式事務,核心流程以下:

1.createTransactionIfNecessary():若是有必要,建立事務

2.InvocationCallbackproceedWithInvocation():InvocationCallback是父類的內部回調接口,子類中實現該接口供父類調用,子類TransactionInterceptorinvocation.proceed()。回調方法執行

3.異常回滾completeTransactionAfterThrowing()

1.createTransactionIfNecessary():

 1 protected TransactionInfo createTransactionIfNecessary(
 2             PlatformTransactionManager tm, TransactionAttribute txAttr, final String joinpointIdentification) {
 3 
 4         // 若是尚未定義名字,把鏈接點的ID定義成事務的名稱
 5         if (txAttr != null && txAttr.getName() == null) {
 6             txAttr = new DelegatingTransactionAttribute(txAttr) {
 7                 @Override
 8                 public String getName() {
 9                     return joinpointIdentification;
10                 }
11             };
12         }
13 
14         TransactionStatus status = null;
15         if (txAttr != null) {
16             if (tm != null) {
17                 status = tm.getTransaction(txAttr);
18             }
19             else {
20                 if (logger.isDebugEnabled()) {
21                     logger.debug("Skipping transactional joinpoint [" + joinpointIdentification +
22                             "] because no transaction manager has been configured");
23                 }
24             }
25         }
26         return prepareTransactionInfo(tm, txAttr, joinpointIdentification, status);
27     }

核心就是:

1)getTransaction(),根據事務屬性獲取事務TransactionStatus,大道歸一,都是調用PlatformTransactionManager.getTransaction(),源碼見3.3.1。
2)prepareTransactionInfo(),構造一個TransactionInfo事務信息對象,綁定當前線程:ThreadLocal<TransactionInfo>。

2.invocation.proceed()回調業務方法:

最終實現類是ReflectiveMethodInvocation,類圖以下:

如上圖,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方法源碼:

 1 @Override
 2     public Object proceed() throws Throwable {
 3         //    啓動時索引爲-1,喚醒鏈接點,後續遞增
 4         if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
 5             return invokeJoinpoint();
 6         }
 7 
 8         Object interceptorOrInterceptionAdvice =
 9                 this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
10         if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) {
11             // 這裏進行動態方法匹配校驗,靜態的方法匹配早已經校驗過了(MethodMatcher接口有兩種典型:動態/靜態校驗)
13             InterceptorAndDynamicMethodMatcher dm =
14                     (InterceptorAndDynamicMethodMatcher) interceptorOrInterceptionAdvice;
15             if (dm.methodMatcher.matches(this.method, this.targetClass, this.arguments)) {
16                 return dm.interceptor.invoke(this);
17             }
18             else {
19                 // 動態匹配失敗,跳過當前攔截,進入下一個(攔截器鏈)
21                 return proceed();
22             }
23         }
24         else {
25             // 它是一個攔截器,因此咱們只調用它:在構造這個對象以前,切入點將被靜態地計算。
27             return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
28         }
29     }

我們這裏最終調用的是((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);就是TransactionInterceptor事務攔截器回調 目標業務方法(addUserBalanceAndUser)。

3.completeTransactionAfterThrowing()

最終調用AbstractPlatformTransactionManager的rollback(),提交事務commitTransactionAfterReturning()最終調用AbstractPlatformTransactionManager的commit(),源碼見3.3.3

總結

可見無論是編程式事務,仍是聲明式事務,最終源碼都是調用事務管理器的PlatformTransactionManager接口的3個方法:

  1. getTransaction
  2. commit
  3. rollback

下一節咱們就來看看這個事務管理如何實現這3個方法。

 

3、事務核心源碼

我們看一下核心類圖:

如上提所示,PlatformTransactionManager頂級接口定義了最核心的事務管理方法,下面一層是AbstractPlatformTransactionManager抽象類,實現了PlatformTransactionManager接口的方法並定義了一些抽象方法,供子類拓展。最後下面一層是2個經典事務管理器:

1.DataSourceTransactionmanager,即JDBC單數據庫事務管理器,基於Connection實現,

2.JtaTransactionManager,即多數據庫事務管理器(又叫作分佈式事務管理器),其實現了JTA規範,使用XA協議進行兩階段提交。

咱們這裏只看基於JDBC connection的DataSourceTransactionmanager源碼。

PlatformTransactionManager接口:

1 public interface PlatformTransactionManager { 2 // 獲取事務狀態 3 TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException; 4   // 事務提交 5 void commit(TransactionStatus status) throws TransactionException; 6   // 事務回滾 7 void rollback(TransactionStatus status) throws TransactionException; 8 }

1. getTransaction獲取事務

AbstractPlatformTransactionManager實現了getTransaction()方法以下:

 1  @Override  2 public final TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException {  3 Object transaction = doGetTransaction();  4  5 // Cache debug flag to avoid repeated checks.  6 boolean debugEnabled = logger.isDebugEnabled();  7  8 if (definition == null) {  9 // Use defaults if no transaction definition given. 10 definition = new DefaultTransactionDefinition(); 11  } 12      // 若是當前已經存在事務 13 if (isExistingTransaction(transaction)) { 14 // 根據不一樣傳播機制不一樣處理 15 return handleExistingTransaction(definition, transaction, debugEnabled); 16  } 17 18 // 超時不能小於默認值 19 if (definition.getTimeout() < TransactionDefinition.TIMEOUT_DEFAULT) { 20 throw new InvalidTimeoutException("Invalid transaction timeout", definition.getTimeout()); 21  } 22 23 // 當前不存在事務,傳播機制=MANDATORY(支持當前事務,沒事務報錯),報錯 24 if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_MANDATORY) { 25 throw new IllegalTransactionStateException( 26 "No existing transaction found for transaction marked with propagation 'mandatory'"); 27  }// 當前不存在事務,傳播機制=REQUIRED/REQUIRED_NEW/NESTED,這三種狀況,須要新開啓事務,且加上事務同步 28 else if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRED || 29 definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRES_NEW || 30 definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NESTED) { 31 SuspendedResourcesHolder suspendedResources = suspend(null); 32 if (debugEnabled) { 33 logger.debug("Creating new transaction with name [" + definition.getName() + "]: " + definition); 34  } 35 try {// 是否須要新開啓同步// 開啓// 開啓 36 boolean newSynchronization = (getTransactionSynchronization() != SYNCHRONIZATION_NEVER); 37 DefaultTransactionStatus status = newTransactionStatus( 38 definition, transaction, true, newSynchronization, debugEnabled, suspendedResources); 39  doBegin(transaction, definition);// 開啓新事務 40  prepareSynchronization(status, definition);//預備同步 41 return status; 42  } 43 catch (RuntimeException ex) { 44 resume(null, suspendedResources); 45 throw ex; 46  } 47 catch (Error err) { 48 resume(null, suspendedResources); 49 throw err; 50  } 51  } 52 else { 53 // 當前不存在事務當前不存在事務,且傳播機制=PROPAGATION_SUPPORTS/PROPAGATION_NOT_SUPPORTED/PROPAGATION_NEVER,這三種狀況,建立「空」事務:沒有實際事務,但多是同步。警告:定義了隔離級別,但並無真實的事務初始化,隔離級別被忽略有隔離級別可是並無定義實際的事務初始化,有隔離級別可是並無定義實際的事務初始化, 54 if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT && logger.isWarnEnabled()) { 55 logger.warn("Custom isolation level specified but no actual transaction initiated; " + 56 "isolation level will effectively be ignored: " + definition); 57  } 58 boolean newSynchronization = (getTransactionSynchronization() == SYNCHRONIZATION_ALWAYS); 59 return prepareTransactionStatus(definition, null, true, newSynchronization, debugEnabled, null); 60  } 61 }

 如上圖,源碼分紅了2條處理線,

1.當前已存在事務:isExistingTransaction()判斷是否存在事務,存在事務handleExistingTransaction()根據不一樣傳播機制不一樣處理

2.當前不存在事務: 不一樣傳播機制不一樣處理

handleExistingTransaction()源碼以下:

 1 private TransactionStatus handleExistingTransaction(
 2             TransactionDefinition definition, Object transaction, boolean debugEnabled)
 3             throws TransactionException {
 4      // 1.NERVER(不支持當前事務;若是當前事務存在,拋出異常)報錯
 5         if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NEVER) {
 6             throw new IllegalTransactionStateException(
 7                     "Existing transaction found for transaction marked with propagation 'never'");
 8         }
 9       // 2.NOT_SUPPORTED(不支持當前事務,現有同步將被掛起)掛起當前事務
10         if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NOT_SUPPORTED) {
11             if (debugEnabled) {
12                 logger.debug("Suspending current transaction");
13             }
14             Object suspendedResources = suspend(transaction);
15             boolean newSynchronization = (getTransactionSynchronization() == SYNCHRONIZATION_ALWAYS);
16             return prepareTransactionStatus(
17                     definition, null, false, newSynchronization, debugEnabled, suspendedResources);
18         }
19       // 3.REQUIRES_NEW掛起當前事務,建立新事務
20         if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRES_NEW) {
21             if (debugEnabled) {
22                 logger.debug("Suspending current transaction, creating new transaction with name [" +
23                         definition.getName() + "]");
24             }// 掛起當前事務
25             SuspendedResourcesHolder suspendedResources = suspend(transaction);
26             try {// 建立新事務
27                 boolean newSynchronization = (getTransactionSynchronization() != SYNCHRONIZATION_NEVER);
28                 DefaultTransactionStatus status = newTransactionStatus(
29                         definition, transaction, true, newSynchronization, debugEnabled, suspendedResources);
30  doBegin(transaction, definition);
31  prepareSynchronization(status, definition);
32                 return status;
33             }
34             catch (RuntimeException beginEx) {
35                 resumeAfterBeginException(transaction, suspendedResources, beginEx);
36                 throw beginEx;
37             }
38             catch (Error beginErr) {
39                 resumeAfterBeginException(transaction, suspendedResources, beginErr);
40                 throw beginErr;
41             }
42         }
43      // 4.NESTED嵌套事務
44         if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NESTED) {
45             if (!isNestedTransactionAllowed()) {
46                 throw new NestedTransactionNotSupportedException(
47                         "Transaction manager does not allow nested transactions by default - " +
48                         "specify 'nestedTransactionAllowed' property with value 'true'");
49             }
50             if (debugEnabled) {
51                 logger.debug("Creating nested transaction with name [" + definition.getName() + "]");
52             }// 是否支持保存點:非JTA事務走這個分支。AbstractPlatformTransactionManager默認是true,JtaTransactionManager複寫了該方法false,DataSourceTransactionmanager沒有複寫,仍是true,
53             if (useSavepointForNestedTransaction()) { 
54                 // Usually uses JDBC 3.0 savepoints. Never activates Spring synchronization.
55                 DefaultTransactionStatus status =
56                         prepareTransactionStatus(definition, transaction, false, false, debugEnabled, null);
57                 status.createAndHoldSavepoint();// 建立保存點
58                 return status;
59             }
60             else {
61                 // JTA事務走這個分支,建立新事務
62                 boolean newSynchronization = (getTransactionSynchronization() != SYNCHRONIZATION_NEVER);
63                 DefaultTransactionStatus status = newTransactionStatus(
64                         definition, transaction, true, newSynchronization, debugEnabled, null);
65  doBegin(transaction, definition);
66  prepareSynchronization(status, definition);
67                 return status;
68             }
69         }
70 
71         
72         if (debugEnabled) {
73             logger.debug("Participating in existing transaction");
74         }
75         if (isValidateExistingTransaction()) {
76             if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) {
77                 Integer currentIsolationLevel = TransactionSynchronizationManager.getCurrentTransactionIsolationLevel();
78                 if (currentIsolationLevel == null || currentIsolationLevel != definition.getIsolationLevel()) {
79                     Constants isoConstants = DefaultTransactionDefinition.constants;
80                     throw new IllegalTransactionStateException("Participating transaction with definition [" +
81                             definition + "] specifies isolation level which is incompatible with existing transaction: " +
82                             (currentIsolationLevel != null ?
83                                     isoConstants.toCode(currentIsolationLevel, DefaultTransactionDefinition.PREFIX_ISOLATION) :
84                                     "(unknown)"));
85                 }
86             }
87             if (!definition.isReadOnly()) {
88                 if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
89                     throw new IllegalTransactionStateException("Participating transaction with definition [" +
90                             definition + "] is not marked as read-only but existing transaction is");
91                 }
92             }
93         }// 到這裏PROPAGATION_SUPPORTS 或 PROPAGATION_REQUIRED或PROPAGATION_MANDATORY,存在事務加入事務便可,prepareTransactionStatus第三個參數就是是否須要新事務。false表明不須要新事物
94         boolean newSynchronization = (getTransactionSynchronization() != SYNCHRONIZATION_NEVER);
95         return prepareTransactionStatus(definition, transaction, false, newSynchronization, debugEnabled, null);
96     }

如上圖,當前線程已存在事務狀況下,新的不一樣隔離級別處理狀況:

1.NERVER:不支持當前事務;若是當前事務存在,拋出異常:"Existing transaction found for transaction marked with propagation 'never'"
2.NOT_SUPPORTED:不支持當前事務,現有同步將被掛起:suspend()
3.REQUIRES_NEW掛起當前事務,建立新事務:

  1)suspend()

  2)doBegin()
4.NESTED嵌套事務

  1)非JTA事務:createAndHoldSavepoint()建立JDBC3.0保存點,不須要同步

  2) JTA事務:開啓新事務,doBegin()+prepareSynchronization()須要同步

 這裏有幾個核心方法:掛起當前事務suspend()、開啓新事務doBegin()。

suspend()源碼以下:

 1 protected final SuspendedResourcesHolder suspend(Object transaction) throws TransactionException {
 2         if (TransactionSynchronizationManager.isSynchronizationActive()) {// 1.當前存在同步,
 3             List<TransactionSynchronization> suspendedSynchronizations = doSuspendSynchronization();
 4             try {
 5                 Object suspendedResources = null;
 6                 if (transaction != null) {// 事務不爲空,掛起事務
 7                     suspendedResources = doSuspend(transaction);
 8                 }// 解除綁定當前事務各類屬性:名稱、只讀、隔離級別、是不是真實的事務.
 9                 String name = TransactionSynchronizationManager.getCurrentTransactionName();
10                 TransactionSynchronizationManager.setCurrentTransactionName(null);
11                 boolean readOnly = TransactionSynchronizationManager.isCurrentTransactionReadOnly();
12                 TransactionSynchronizationManager.setCurrentTransactionReadOnly(false);
13                 Integer isolationLevel = TransactionSynchronizationManager.getCurrentTransactionIsolationLevel();
14                 TransactionSynchronizationManager.setCurrentTransactionIsolationLevel(null);
15                 boolean wasActive = TransactionSynchronizationManager.isActualTransactionActive();
16                 TransactionSynchronizationManager.setActualTransactionActive(false);
17                 return new SuspendedResourcesHolder(
18                         suspendedResources, suspendedSynchronizations, name, readOnly, isolationLevel, wasActive);
19             }
20             catch (RuntimeException ex) {
21                 // doSuspend failed - original transaction is still active...
22                 doResumeSynchronization(suspendedSynchronizations);
23                 throw ex;
24             }
25             catch (Error err) {
26                 // doSuspend failed - original transaction is still active...
27                 doResumeSynchronization(suspendedSynchronizations);
28                 throw err;
29             }
30         }// 2.沒有同步但,事務不爲空,掛起事務
31         else if (transaction != null) {
32             // Transaction active but no synchronization active.
33             Object suspendedResources = doSuspend(transaction);
34             return new SuspendedResourcesHolder(suspendedResources);
35         }// 2.沒有同步但,事務爲空,什麼都不用作
36         else {
37             // Neither transaction nor synchronization active.
38             return null;
39         }
40     }

doSuspend(),掛起事務,AbstractPlatformTransactionManager抽象類doSuspend()會報錯:不支持掛起,若是具體事務執行器支持就複寫doSuspend(),DataSourceTransactionManager實現以下:

1 @Override
2     protected Object doSuspend(Object transaction) {
3         DataSourceTransactionObject txObject = (DataSourceTransactionObject) transaction;
4         txObject.setConnectionHolder(null);
5         return TransactionSynchronizationManager.unbindResource(this.dataSource);
6     }

掛起DataSourceTransactionManager事務的核心操做就是:

1.把當前事務的connectionHolder數據庫鏈接持有者清空。

2.當前線程解綁datasource.其實就是ThreadLocal移除對應變量(TransactionSynchronizationManager類中定義的private static final ThreadLocal<Map<Object, Object>> resources = new NamedThreadLocal<Map<Object, Object>>("Transactional resources");

TransactionSynchronizationManager事務同步管理器,該類維護了多個線程本地變量ThreadLocal,以下圖:

 1 public abstract class TransactionSynchronizationManager {  2  3 private static final Log logger = LogFactory.getLog(TransactionSynchronizationManager.class);  4 // 事務資源:map<k,v> 兩種數據對。1.會話工廠和會話k=SqlsessionFactory v=SqlSessionHolder 2.數據源和鏈接k=DataSource v=ConnectionHolder  5 private static final ThreadLocal<Map<Object, Object>> resources =  6 new NamedThreadLocal<Map<Object, Object>>("Transactional resources");  7 // 事務同步  8 private static final ThreadLocal<Set<TransactionSynchronization>> synchronizations =  9 new NamedThreadLocal<Set<TransactionSynchronization>>("Transaction synchronizations"); 10   // 當前事務名稱 11 private static final ThreadLocal<String> currentTransactionName = 12 new NamedThreadLocal<String>("Current transaction name"); 13   // 當前事務的只讀屬性 14 private static final ThreadLocal<Boolean> currentTransactionReadOnly = 15 new NamedThreadLocal<Boolean>("Current transaction read-only status"); 16   // 當前事務的隔離級別 17 private static final ThreadLocal<Integer> currentTransactionIsolationLevel = 18 new NamedThreadLocal<Integer>("Current transaction isolation level"); 19   // 是否存在事務 20 private static final ThreadLocal<Boolean> actualTransactionActive = 21 new NamedThreadLocal<Boolean>("Actual transaction active"); 22 。。。 23 }

doBegin()源碼以下:

 1 @Override
 2     protected void doBegin(Object transaction, TransactionDefinition definition) {
 3         DataSourceTransactionObject txObject = (DataSourceTransactionObject) transaction;
 4         Connection con = null;
 5 
 6         try {// 若是事務尚未connection或者connection在事務同步狀態,重置新的connectionHolder
 7             if (!txObject.hasConnectionHolder() ||
 8                     txObject.getConnectionHolder().isSynchronizedWithTransaction()) {
 9                 Connection newCon = this.dataSource.getConnection();
10                 if (logger.isDebugEnabled()) {
11                     logger.debug("Acquired Connection [" + newCon + "] for JDBC transaction");
12                 }// 重置新的connectionHolder
13                 txObject.setConnectionHolder(new ConnectionHolder(newCon), true);
14             }
15        //設置新的鏈接爲事務同步中
16             txObject.getConnectionHolder().setSynchronizedWithTransaction(true);
17             con = txObject.getConnectionHolder().getConnection();
18          //conn設置事務隔離級別,只讀
19             Integer previousIsolationLevel = DataSourceUtils.prepareConnectionForTransaction(con, definition);
20             txObject.setPreviousIsolationLevel(previousIsolationLevel);//DataSourceTransactionObject設置事務隔離級別
21 
22             // 若是是自動提交切換到手動提交
23             // so we don't want to do it unnecessarily (for example if we've explicitly
24             // configured the connection pool to set it already).
25             if (con.getAutoCommit()) {
26                 txObject.setMustRestoreAutoCommit(true);
27                 if (logger.isDebugEnabled()) {
28                     logger.debug("Switching JDBC Connection [" + con + "] to manual commit");
29                 }
30                 con.setAutoCommit(false);
31             }
32        // 若是隻讀,執行sql設置事務只讀
33             prepareTransactionalConnection(con, definition);
34             txObject.getConnectionHolder().setTransactionActive(true);// 設置connection持有者的事務開啓狀態
35 
36             int timeout = determineTimeout(definition);
37             if (timeout != TransactionDefinition.TIMEOUT_DEFAULT) {
38                 txObject.getConnectionHolder().setTimeoutInSeconds(timeout);// 設置超時秒數
39             }
40 
41             // 綁定connection持有者到當前線程
42             if (txObject.isNewConnectionHolder()) {
43                 TransactionSynchronizationManager.bindResource(getDataSource(), txObject.getConnectionHolder());
44             }
45         }
46 
47         catch (Throwable ex) {
48             if (txObject.isNewConnectionHolder()) {
49                 DataSourceUtils.releaseConnection(con, this.dataSource);
50                 txObject.setConnectionHolder(null, false);
51             }
52             throw new CannotCreateTransactionException("Could not open JDBC Connection for transaction", ex);
53         }
54     }

如上圖,開啓新事務的準備工做doBegin()的核心操做就是:

1.DataSourceTransactionObject「數據源事務對象」,設置ConnectionHolder,再給ConnectionHolder設置各類屬性:自動提交、超時、事務開啓、隔離級別。

2.給當前線程綁定一個線程本地變量,key=DataSource數據源  v=ConnectionHolder數據庫鏈接。

 

2. commit提交事務

1、講解源碼以前先看一下資源管理類:

SqlSessionSynchronization是SqlSessionUtils的一個內部類,繼承自TransactionSynchronizationAdapter抽象類,實現了事務同步接口TransactionSynchronization

類圖以下:

TransactionSynchronization接口定義了事務操做時的對應資源的(JDBC事務那麼就是SqlSessionSynchronization)管理方法:

 1     // 掛起事務   
2   void suspend(); 3 // 喚醒事務    4   void resume(); 5 6 void flush(); 7 8 // 提交事務前 9 void beforeCommit(boolean readOnly); 10 11 // 提交事務完成前 12 void beforeCompletion(); 13 14 // 提交事務後 15 void afterCommit(); 16 17 // 提交事務完成後 18 void afterCompletion(int status);

後續不少都是使用這些接口管理事務。

2、 commit提交事務

 

AbstractPlatformTransactionManager的commit源碼以下:

 1 @Override
 2     public final void commit(TransactionStatus status) throws TransactionException {
 3         if (status.isCompleted()) {// 若是事務已完結,報錯沒法再次提交
 4             throw new IllegalTransactionStateException(
 5                     "Transaction is already completed - do not call commit or rollback more than once per transaction");
 6         }
 7 
 8         DefaultTransactionStatus defStatus = (DefaultTransactionStatus) status;
 9         if (defStatus.isLocalRollbackOnly()) {// 若是事務明確標記爲回滾,
10             if (defStatus.isDebug()) {
11                 logger.debug("Transactional code has requested rollback");
12             }
13  processRollback(defStatus);//執行回滾
14             return;
15         }//若是不須要全局回滾時提交 且 全局回滾
16         if (!shouldCommitOnGlobalRollbackOnly() && defStatus.isGlobalRollbackOnly()) {
17             if (defStatus.isDebug()) {
18                 logger.debug("Global transaction is marked as rollback-only but transactional code requested commit");
19             }//執行回滾
20  processRollback(defStatus);
21             // 僅在最外層事務邊界(新事務)或顯式地請求時拋出「未指望的回滾異常」
23             if (status.isNewTransaction() || isFailEarlyOnGlobalRollbackOnly()) {
24                 throw new UnexpectedRollbackException(
25                         "Transaction rolled back because it has been marked as rollback-only");
26             }
27             return;
28         }
29      // 執行提交事務
30  processCommit(defStatus);
31     }

如上圖,各類判斷:

  • 1.若是事務明確標記爲本地回滾,-》執行回滾
  • 2.若是不須要全局回滾時提交 且 全局回滾-》執行回滾
  • 3.提交事務,核心方法processCommit()

processCommit以下:

 1 private void processCommit(DefaultTransactionStatus status) throws TransactionException {
 2         try {
 3             boolean beforeCompletionInvoked = false;
 4             try {//3個前置操做
 5  prepareForCommit(status);
 6  triggerBeforeCommit(status);
 7  triggerBeforeCompletion(status);
 8                 beforeCompletionInvoked = true;//3個前置操做已調用
 9                 boolean globalRollbackOnly = false;//新事務 或 全局回滾失敗
10                 if (status.isNewTransaction() || isFailEarlyOnGlobalRollbackOnly()) {
11                     globalRollbackOnly = status.isGlobalRollbackOnly();
12                 }//1.有保存點,即嵌套事務
13                 if (status.hasSavepoint()) {
14                     if (status.isDebug()) {
15                         logger.debug("Releasing transaction savepoint");
16                     }//釋放保存點
17                     status.releaseHeldSavepoint();
18                 }//2.新事務
19                 else if (status.isNewTransaction()) {
20                     if (status.isDebug()) {
21                         logger.debug("Initiating transaction commit");
22                     }//調用事務處理器提交事務
23  doCommit(status);
24                 }
25                 // 3.非新事務,且全局回滾失敗,可是提交時沒有獲得異常,拋出異常
27                 if (globalRollbackOnly) {
28                     throw new UnexpectedRollbackException(
29                             "Transaction silently rolled back because it has been marked as rollback-only");
30                 }
31             }
32             catch (UnexpectedRollbackException ex) {
33                 // 觸發完成後事務同步,狀態爲回滾
34  triggerAfterCompletion(status, TransactionSynchronization.STATUS_ROLLED_BACK);
35                 throw ex;
36             }// 事務異常
37             catch (TransactionException ex) {
38                 // 提交失敗回滾
39                 if (isRollbackOnCommitFailure()) {
40  doRollbackOnCommitException(status, ex);
41                 }// 觸發完成後回調,事務同步狀態爲未知
42                 else {
43  triggerAfterCompletion(status, TransactionSynchronization.STATUS_UNKNOWN);
44                 }
45                 throw ex;
46             }// 運行時異常
47             catch (RuntimeException ex) {
            // 若是3個前置步驟未完成,調用前置的最後一步操做
48 if (!beforeCompletionInvoked) { 49 triggerBeforeCompletion(status); 50 }// 提交異常回滾 51 doRollbackOnCommitException(status, ex); 52 throw ex; 53 }// 其它異常 54 catch (Error err) {  
            // 若是3個前置步驟未完成,調用前置的最後一步操做
55 if (!beforeCompletionInvoked) { 56 triggerBeforeCompletion(status); 57 }// 提交異常回滾 58 doRollbackOnCommitException(status, err); 59 throw err; 60 } 61 62 // Trigger afterCommit callbacks, with an exception thrown there 63 // propagated to callers but the transaction still considered as committed. 64 try { 65 triggerAfterCommit(status); 66 } 67 finally { 68 triggerAfterCompletion(status, TransactionSynchronization.STATUS_COMMITTED); 69 } 70 71 } 72 finally { 73 cleanupAfterCompletion(status); 74 } 75 }

如上圖,commit事務時,有6個核心操做,分別是3個前置操做,3個後置操做,以下:

1.prepareForCommit(status);源碼是空的,沒有拓展目前。

2.triggerBeforeCommit(status); 提交前觸發操做

1 protected final void triggerBeforeCommit(DefaultTransactionStatus status) {
2         if (status.isNewSynchronization()) {
3             if (status.isDebug()) {
4                 logger.trace("Triggering beforeCommit synchronization");
5             }
6             TransactionSynchronizationUtils.triggerBeforeCommit(status.isReadOnly());
7         }
8     }

triggerBeforeCommit源碼以下:

1 public static void triggerBeforeCommit(boolean readOnly) {
2         for (TransactionSynchronization synchronization : TransactionSynchronizationManager.getSynchronizations()) {
3             synchronization.beforeCommit(readOnly);
4         }
5     }

 如上圖,TransactionSynchronizationManager類定義了多個ThreadLocal(線程本地變量),其中一個用以保存當前線程的事務同步:

private static final ThreadLocal<Set<TransactionSynchronization>> synchronizations = new NamedThreadLocal<Set<TransactionSynchronization>>("Transaction synchronizations");

遍歷事務同步器,把每一個事務同步器都執行「提交前」操做,好比我們用的jdbc事務,那麼最終就是SqlSessionUtils.beforeCommit()->this.holder.getSqlSession().commit();提交會話。

3.triggerBeforeCompletion(status);完成前觸發操做,若是是jdbc事務,那麼最終就是

SqlSessionUtils.beforeCompletion->

TransactionSynchronizationManager.unbindResource(sessionFactory); 解綁當前線程的會話工廠

this.holder.getSqlSession().close();關閉會話。

4.triggerAfterCommit(status);提交事務後觸發操做。TransactionSynchronizationUtils.triggerAfterCommit();->TransactionSynchronizationUtils.invokeAfterCommit,以下:

1 public static void invokeAfterCommit(List<TransactionSynchronization> synchronizations) {
2         if (synchronizations != null) {
3             for (TransactionSynchronization synchronization : synchronizations) {
4                 synchronization.afterCommit();
5             }
6         }
7     }

好吧,一頓找,最後在TransactionSynchronizationAdapter中複寫過,而且是空的....SqlSessionSynchronization繼承了TransactionSynchronizationAdapter可是沒有複寫這個方法。

5. triggerAfterCompletion(status, TransactionSynchronization.STATUS_COMMITTED);

TransactionSynchronizationUtils.TransactionSynchronizationUtils.invokeAfterCompletion,以下:

 1 public static void invokeAfterCompletion(List<TransactionSynchronization> synchronizations, int completionStatus) {
 2         if (synchronizations != null) {
 3             for (TransactionSynchronization synchronization : synchronizations) {
 4                 try {
 5                     synchronization.afterCompletion(completionStatus);  6                 }
 7                 catch (Throwable tsex) {
 8                     logger.error("TransactionSynchronization.afterCompletion threw exception", tsex);
 9                 }
10             }
11         }
12     }

afterCompletion:對於JDBC事務來講,最終:

1)若是會話任然活着,關閉會話,

2)重置各類屬性:SQL會話同步器(SqlSessionSynchronization)的SQL會話持有者(SqlSessionHolder)的referenceCount引用計數、synchronizedWithTransaction同步事務、rollbackOnly只回滾、deadline超時時間點。

6.cleanupAfterCompletion(status);

1)設置事務狀態爲已完成。

2)  若是是新的事務同步,解綁當前線程綁定的數據庫資源,重置數據庫鏈接

3)若是存在掛起的事務(嵌套事務),喚醒掛起的老事務的各類資源:數據庫資源、同步器。

 1     private void cleanupAfterCompletion(DefaultTransactionStatus status) {
 2         status.setCompleted();//設置事務狀態完成
       //若是是新的同步,清空當前線程綁定的除了資源外的所有線程本地變量:包括事務同步器、事務名稱、只讀屬性、隔離級別、真實的事務激活狀態
3 if (status.isNewSynchronization()) { 4 TransactionSynchronizationManager.clear(); 5 }//若是是新的事務同步 6 if (status.isNewTransaction()) { 7 doCleanupAfterCompletion(status.getTransaction()); 8 }//若是存在掛起的資源 9 if (status.getSuspendedResources() != null) { 10 if (status.isDebug()) { 11 logger.debug("Resuming suspended transaction after completion of inner transaction"); 12 }//喚醒掛起的事務和資源(從新綁定以前掛起的數據庫資源,喚醒同步器,註冊同步器到TransactionSynchronizationManager) 13 resume(status.getTransaction(), (SuspendedResourcesHolder) status.getSuspendedResources()); 14 } 15 }

對於DataSourceTransactionManager,doCleanupAfterCompletion源碼以下:

 1     protected void doCleanupAfterCompletion(Object transaction) {
 2         DataSourceTransactionObject txObject = (DataSourceTransactionObject) transaction;
 3 
 4         // 若是是最新的鏈接持有者,解綁當前線程綁定的<數據庫資源,ConnectionHolder>
 5         if (txObject.isNewConnectionHolder()) {
 6             TransactionSynchronizationManager.unbindResource(this.dataSource);
 7         }
 8 
 9         // 重置數據庫鏈接(隔離級別、只讀)
10         Connection con = txObject.getConnectionHolder().getConnection();
11         try {
12             if (txObject.isMustRestoreAutoCommit()) {
13                 con.setAutoCommit(true);
14             }
15             DataSourceUtils.resetConnectionAfterTransaction(con, txObject.getPreviousIsolationLevel());
16         }
17         catch (Throwable ex) {
18             logger.debug("Could not reset JDBC Connection after transaction", ex);
19         }
20 
21         if (txObject.isNewConnectionHolder()) {
22             if (logger.isDebugEnabled()) {
23                 logger.debug("Releasing JDBC Connection [" + con + "] after transaction");
24             }// 資源引用計數-1,關閉數據庫鏈接
25             DataSourceUtils.releaseConnection(con, this.dataSource);
26         }
27         // 重置鏈接持有者的所有屬性
28         txObject.getConnectionHolder().clear();
29     }

 

3. rollback回滾事務

 AbstractPlatformTransactionManager中rollback源碼以下:

1     public final void rollback(TransactionStatus status) throws TransactionException {
2         if (status.isCompleted()) {
3             throw new IllegalTransactionStateException(
4                     "Transaction is already completed - do not call commit or rollback more than once per transaction");
5         }
6 
7         DefaultTransactionStatus defStatus = (DefaultTransactionStatus) status;
8  processRollback(defStatus);
9     }

 processRollback源碼以下:

 1     private void processRollback(DefaultTransactionStatus status) {
 2         try {
 3             try {// 解綁當前線程綁定的會話工廠,並關閉會話
 4  triggerBeforeCompletion(status);
 5                 if (status.hasSavepoint()) {// 1.若是有保存點,即嵌套式事務
 6                     if (status.isDebug()) {
 7                         logger.debug("Rolling back transaction to savepoint");
 8                     }//回滾到保存點
 9                     status.rollbackToHeldSavepoint();
10                 }//2.若是就是一個簡單事務
11                 else if (status.isNewTransaction()) {
12                     if (status.isDebug()) {
13                         logger.debug("Initiating transaction rollback");
14                     }//回滾核心方法
15  doRollback(status);
16                 }//3.當前存在事務且沒有保存點,即加入當前事務的
17                 else if (status.hasTransaction()) {//若是已經標記爲回滾 或 當加入事務失敗時全局回滾(默認true)
18                     if (status.isLocalRollbackOnly() || isGlobalRollbackOnParticipationFailure()) {
19                         if (status.isDebug()) {//debug時會打印:加入事務失敗-標記已存在事務爲回滾
20                             logger.debug("Participating transaction failed - marking existing transaction as rollback-only");
21                         }//設置當前connectionHolder:當加入一個已存在事務時回滾
22  doSetRollbackOnly(status);
23                     }
24                     else {
25                         if (status.isDebug()) {
26                             logger.debug("Participating transaction failed - letting transaction originator decide on rollback");
27                         }
28                     }
29                 }
30                 else {
31                     logger.debug("Should roll back transaction but cannot - no transaction available");
32                 }
33             }
34             catch (RuntimeException ex) {//關閉會話,重置SqlSessionHolder屬性
35  triggerAfterCompletion(status, TransactionSynchronization.STATUS_UNKNOWN);
36                 throw ex;
37             }
38             catch (Error err) {
39                 triggerAfterCompletion(status, TransactionSynchronization.STATUS_UNKNOWN);
40                 throw err;
41             }
42             triggerAfterCompletion(status, TransactionSynchronization.STATUS_ROLLED_BACK);
43         }
44         finally {、、解綁當前線程
45  cleanupAfterCompletion(status);
46         }
47     }

如上圖,有幾個公共方法和提交事務時一致,就再也不重複。

這裏主要看doRollback,DataSourceTransactionManager的doRollback()源碼以下:

 1 protected void doRollback(DefaultTransactionStatus status) {
 2         DataSourceTransactionObject txObject = (DataSourceTransactionObject) status.getTransaction();
 3         Connection con = txObject.getConnectionHolder().getConnection();
 4         if (status.isDebug()) {
 5             logger.debug("Rolling back JDBC transaction on Connection [" + con + "]");
 6         }
 7         try {
 8             con.rollback();
 9         }
10         catch (SQLException ex) {
11             throw new TransactionSystemException("Could not roll back JDBC transaction", ex);
12         }
13     }

好吧,一點不復雜,就是Connection的rollback.

 4、時序圖

特意整理了時序圖(簡單的新事務,沒有畫出保存點等狀況)以下:

 

===========參考========

《Spring實戰4》第四章 面向切面的Spring  

SpringBoot事務註解@Transactional

相關文章
相關標籤/搜索