Spring事務傳播特性的淺析——事務方法嵌套調用的迷茫


 

Spring事務傳播機制回顧 


   Spring事務一個被訛傳很廣說法是:一個事務方法不應該調用另一個事務方法,否則將產生兩個事務。結果造成開發人員在設計事務方法時束手束腳,生怕一不小心就踩到地雷。 
其實這是不認識Spring事務傳播機制而造成的誤解,Spring對事務控制的支持統一在TransactionDefinition類中描述,該類有以下幾個重要的接口方法: 

  • int getPropagationBehavior():事務的傳播行為
  • int getIsolationLevel():事務的隔離級別
  • int getTimeout():事務的過期時間
  • boolean isReadOnly():事務的讀寫特性



   很明顯,除了事務的傳播行為外,事務的其他特性Spring是借助底層資源的功能來完成的,Spring無非只充當個代理的角色。但是事務的傳播行為卻是Spring憑借自身的框架提供的功能,是Spring提供給開發者最珍貴的禮物,訛傳的說法玷污了Spring事務框架最美麗的光環。 
   
   所謂事務傳播行為就是多個事務方法相互調用時,事務如何在這些方法間傳播。Spring支持以下7種事務傳播行為。 

  • PROPAGATION_REQUIRED:如果當前沒有事務,就新建一個事務,如果已經存在一個事務,就加入到這個事務中。這是最常見的選擇。
  • PROPAGATION_SUPPORTS:支持當前事務,如果當前沒有事務,就以非事務方式執行。
  • PROPAGATION_MANDATORY:使用當前的事務,如果當前沒有事務,就拋出異常。
  • PROPAGATION_REQUIRES_NEW:新建事務,如果當前存在事務,把當前事務掛起。
  • PROPAGATION_NOT_SUPPORTED:以非事務方式執行操作,如果當前存在事務,就把當前事務掛起。
  • PROPAGATION_NEVER:以非事務方式執行,如果當前存在事務,則拋出異常。
  • PROPAGATION_NESTED:如果當前存在事務,則在嵌套事務內執行。如果當前沒有事務,則執行與PROPAGATION_REQUIRED類似的操作。



   Spring默認的事務傳播行為是PROPAGATION_REQUIRED,它適合絕大多數的情況,如果多個ServiveX#methodX()均工作在事務環境下(即均被Spring事務增強),且程序中存在如下的調用鏈:Service1#method1()->Service2#method2()->Service3#method3(),那么這3個服務類的3個方法通過Spring的事務傳播機制都工作在同一個事務中。 

相互嵌套的服務方法 
   

   我們來看一下實例,UserService#logon()方法內部調用了UserService#updateLastLogon Time()和ScoreService#addScore()方法,這兩個類都繼承於BaseService。它們之間的類結構如下圖所示:

   UserService#logon()方法內部調用了ScoreService#addScore()的方法,兩者都分別通過Spring AOP進行了事務增強,則它們工作於同一事務中。來看具體的代碼: 

 

package com.baobaotao.nestcall;
…
@Service("userService")
public class UserService extends BaseService {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private ScoreService scoreService;
    
    //①該方法嵌套調用了本類的其他方法及其他服務類的方法
    public void logon(String userName) {
        System.out.println("before userService.updateLastLogonTime...");
        updateLastLogonTime(userName);//①-1本服務類的其他方法
        System.out.println("after userService.updateLastLogonTime...");
        
        System.out.println("before scoreService.addScore...");
        scoreService.addScore(userName, 20); //①-2其他服務類的其他方法
        System.out.println("after scoreService.addScore...");

    }
    public void updateLastLogonTime(String userName) {
        String sql = "UPDATE t_user u SET u.last_logon_time = ? WHERE user_name =?";
        jdbcTemplate.update(sql, System.currentTimeMillis(), userName);
    }

 

UserService中注入了ScoreService的Bean,而ScoreService的代碼如下所示: 

 

package com.baobaotao.nestcall;
…
@Service("scoreUserService")
public class ScoreService extends BaseService{

    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    public void addScore(String userName, int toAdd) {
        String sql = "UPDATE t_user u SET u.score = u.score + ? WHERE user_name =?";
        jdbcTemplate.update(sql, toAdd, userName);
    }
}

  通過Spring配置為ScoreService及UserService中所有公有方法都添加Spring AOP的事務增強,讓UserService的logon()和updateLastLogonTime()及ScoreService的addScore()方法都工作於事務環境下。下面是關鍵的配置代碼: 

 

<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
    <context:component-scan base-package="com.baobaotao.nestcall"/><bean id="jdbcManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
          p:dataSource-ref="dataSource"/>

    <!--①通過以下配置為所有繼承BaseService類的所有子類的所有public方法都添加事務增強-->
    <aop:config proxy-target-class="true">
        <aop:pointcut id="serviceJdbcMethod"
                      expression="within(com.baobaotao.nestcall.BaseService+)"/>
        <aop:advisor pointcut-ref="serviceJdbcMethod" advice-ref="jdbcAdvice" order="0"/>
    </aop:config>
    <tx:advice id="jdbcAdvice" transaction-manager="jdbcManager">
        <tx:attributes>
            <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>
</beans>

將日志級別設置為DEBUG,啟動Spring容器並執行UserService#logon()的方法,仔細觀察如下輸出日志: 

 

before userService.logon method... 

     //①創建了一個事務 
Creating new transaction with name [com.baobaotao.nestcall.UserService.logon]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT 
Acquired Connection [jdbc:mysql://localhost:3306/sampledb, UserName=root@localhost, MySQL-AB JDBC Driver] for JDBC transaction 
Switching JDBC Connection [jdbc:mysql://localhost:3306/sampledb, UserName=root@localhost, MySQL-AB JDBC Driver] to manual commit 
before userService.updateLastLogonTime... 

    <!--②updateLastLogonTime()和logon()在同一個Bean中,並未發生加入已存在事務上下文的 
      動作,而是“天然”地工作於相同的事務上下文--> 
Executing prepared SQL update 
Executing prepared SQL statement [UPDATE t_user u SET u.last_logon_time = ? WHERE user_name =?] 
SQL update affected 1 rows 
after userService.updateLastLogonTime... 
before scoreService.addScore... 

//③ScoreService#addScore方法加入到①處啟動的事務上下文中 
Participating in existing transaction Executing prepared SQL update 
Executing prepared SQL statement [UPDATE t_user u SET u.score = u.score + ? WHERE user_name =?] 
SQL update affected 1 rows 
after scoreService.addScore... 
Initiating transaction commit 
Committing JDBC transaction on Connection [jdbc:mysql://localhost:3306/sampledb, UserName=root@localhost, MySQL-AB JDBC Driver] 
… 
after userService.logon method... 

 

從上面的輸出日志中,可以清楚地看到Spring為UserService#logon()方法啟動了一個新的事務,而UserSerive#updateLastLogonTime()和UserService#logon()是在相同的類中,沒有觀察到有事務傳播行為的發生,其代碼塊好像“直接合並”到UserService#logon()中。 

然而在執行到ScoreService#addScore()方法時,我們就觀察到發生一個事務傳播的行為:" Participating in existing transaction ",
這說明ScoreService#addScore()添加到UserService#logon()的事務上下文中,兩者共享同一個事務
所以最終的結果是UserService的logon()、updateLastLogonTime()以及ScoreService的addScore都工作於同一事務中。 

 

注:以上內容摘自《Spring 3.x企業應用開發實戰》 

http://blog.csdn.net/hy6688_/article/details/44763869

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM