Spring事務隔離級別和傳播特性


相信每個人都被問過無數次Spring聲明式事務的隔離級別和傳播機制吧!今天我也來說說這兩個東西.

加入一個小插曲,
一天電話里有人問我聲明式事務隔離級別有哪幾種,
我就回答了7種,
他問我Spring的版本,
我回答為3.0。
他說那應該是2.5的,3.0好像變少了。
我回答這個沒有確認過。

后來我就google了一下,沒發現什么痕跡說明事務的隔離級別變少了,也查了下官方文檔,也沒有相關的說明。索性在github上clone一下Spring的源碼,看看源碼中有幾種就是幾種了唄。

后來想想那天他那么問我完全可能是一個坑啊,因為交談的過程中挖過至少兩個坑了。再者說,Spring要向下兼容的,如果少了怎么處理呢?當然這兩點都是我自己的猜測。

聲明式事務

在Spring中,聲明式事務是用事務參數來定義的。一個事務參數就是對事務策略應該如何應用到某個方法的一段描述,如下圖所示一個事務參數共有5個方面組成:

傳播行為

事務的第一個方面是傳播行為。傳播行為定義關於客戶端和被調用方法的事務邊界。Spring定義了7中傳播行為。

傳播行為 意義
PROPAGATION_MANDATORY 表示該方法必須運行在一個事務中。如果當前沒有事務正在發生,將拋出一個異常
PROPAGATION_NESTED 表示如果當前正有一個事務在進行中,則該方法應當運行在一個嵌套式事務中。被嵌套的事務可以獨立於封裝事務進行提交或回滾。如果封裝事務不存在,行為就像PROPAGATION_REQUIRES一樣。
PROPAGATION_NEVER 表示當前的方法不應該在一個事務中運行。如果一個事務正在進行,則會拋出一個異常。
PROPAGATION_NOT_SUPPORTED 表示該方法不應該在一個事務中運行。如果一個現有事務正在進行中,它將在該方法的運行期間被掛起。
PROPAGATION_SUPPORTS 表示當前方法不需要事務性上下文,但是如果有一個事務已經在運行的話,它也可以在這個事務里運行。
PROPAGATION_REQUIRES_NEW 表示當前方法必須在它自己的事務里運行。一個新的事務將被啟動,而且如果有一個現有事務在運行的話,則將在這個方法運行期間被掛起。
PROPAGATION_REQUIRES 表示當前方法必須在一個事務中運行。如果一個現有事務正在進行中,該方法將在那個事務中運行,否則就要開始一個新事務。

傳播規則回答了這樣一個問題,就是一個新的事務應該被啟動還是被掛起,或者是一個方法是否應該在事務性上下文中運行。

隔離級別

聲明式事務的第二個方面是隔離級別。隔離級別定義一個事務可能受其他並發事務活動活動影響的程度。另一種考慮一個事務的隔離級別的方式,是把它想象為那個事務對於事物處理數據的自私程度。

在一個典型的應用程序中,多個事務同時運行,經常會為了完成他們的工作而操作同一個數據。並發雖然是必需的,但是會導致一下問題:

  • 臟讀(Dirty read)-- 臟讀發生在一個事務讀取了被另一個事務改寫但尚未提交的數據時。如果這些改變在稍后被回滾了,那么第一個事務讀取的數據就會是無效的。
  • 不可重復讀(Nonrepeatable read)-- 不可重復讀發生在一個事務執行相同的查詢兩次或兩次以上,但每次查詢結果都不相同時。這通常是由於另一個並發事務在兩次查詢之間更新了數據。
  • 幻影讀(Phantom reads)-- 幻影讀和不可重復讀相似。當一個事務(T1)讀取幾行記錄后,另一個並發事務(T2)插入了一些記錄時,幻影讀就發生了。在后來的查詢中,第一個事務(T1)就會發現一些原來沒有的額外記錄。

在理想狀態下,事務之間將完全隔離,從而可以防止這些問題發生。然而,完全隔離會影響性能,因為隔離經常牽扯到鎖定在數據庫中的記錄(而且有時是鎖定完整的數據表)。侵占性的鎖定會阻礙並發,要求事務相互等待來完成工作。

考慮到完全隔離會影響性能,而且並不是所有應用程序都要求完全隔離,所以有時可以在事務隔離方面靈活處理。因此,就會有好幾個隔離級別。

隔離級別 含義
ISOLATION_DEFAULT 使用后端數據庫默認的隔離級別。
ISOLATION_READ_UNCOMMITTED 允許讀取尚未提交的更改。可能導致臟讀、幻影讀或不可重復讀。
ISOLATION_READ_COMMITTED 允許從已經提交的並發事務讀取。可防止臟讀,但幻影讀和不可重復讀仍可能會發生。
ISOLATION_REPEATABLE_READ 對相同字段的多次讀取的結果是一致的,除非數據被當前事務本身改變。可防止臟讀和不可重復讀,但幻影讀仍可能發生。
ISOLATION_SERIALIZABLE 完全服從ACID的隔離級別,確保不發生臟讀、不可重復讀和幻影讀。這在所有隔離級別中也是最慢的,因為它通常是通過完全鎖定當前事務所涉及的數據表來完成的。

只讀

聲明式事務的第三個特性是它是否是一個只讀事務。如果一個事務只對后端數據庫執行讀操作,那么該數據庫就可能利用那個事務的只讀特性,采取某些優化 措施。通過把一個事務聲明為只讀,可以給后端數據庫一個機會來應用那些它認為合適的優化措施。由於只讀的優化措施是在一個事務啟動時由后端數據庫實施的, 因此,只有對於那些具有可能啟動一個新事務的傳播行為(PROPAGATION_REQUIRES_NEW、PROPAGATION_REQUIRED、 ROPAGATION_NESTED)的方法來說,將事務聲明為只讀才有意義。

此外,如果使用Hibernate作為持久化機制,那么把一個事務聲明為只讀,將使Hibernate的flush模式被設置為FLUSH_NEVER。這就告訴Hibernate避免和數據庫進行不必要的對象同步,從而把所有更新延遲到事務的結束。

事務超時

為了使一個應用程序很好地執行,它的事務不能運行太長時間。因此,聲明式事務的下一個特性就是它的超時。

假設事務的運行時間變得格外的長,由於事務可能涉及對后端數據庫的鎖定,所以長時間運行的事務會不必要地占用數據庫資源。這時就可以聲明一個事務在特定秒數后自動回滾,不必等它自己結束。

由於超時時鍾在一個事務啟動的時候開始的,因此,只有對於那些具有可能啟動一個新事務的傳播行為(PROPAGATION_REQUIRES_NEW、PROPAGATION_REQUIRED、ROPAGATION_NESTED)的方法來說,聲明事務超時才有意義。

回滾規則

事務五邊形的對后一個邊是一組規則,它們定義哪些異常引起回滾,哪些不引起。在默認設置下,事務只在出現運行時異常(runtime exception)時回滾,而在出現受檢查異常(checked exception)時不回滾(這一行為和EJB中的回滾行為是一致的)。

不過,也可以聲明在出現特定受檢查異常時像運行時異常一樣回滾。同樣,也可以聲明一個事務在出現特定的異常時不回滾,即使那些異常是運行時一場。

擴展閱讀

標題是只有事務的隔離級別和傳播機制,卻順帶這把聲明式事務的五個特性都講述了一遍。:)

文章開頭說過查看Spring中事務的源碼來確認3.0版本及之后事務的傳播機制是否減少了,其實在TransactionDefinition這個接口中定義了事務的隔離級別、傳播機制、只讀以及超時相關的全部信息。源碼如下,感興趣的可以自己對照一下,看看英文注釋。

/*
 * Copyright 2002-2010 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.transaction;

import java.sql.Connection;

/**
 * Interface that defines Spring-compliant transaction properties.
 * Based on the propagation behavior definitions analogous to EJB CMT attributes.
 *
 * <p>Note that isolation level and timeout settings will not get applied unless
 * an actual new transaction gets started. As only {@link #PROPAGATION_REQUIRED},
 * {@link #PROPAGATION_REQUIRES_NEW} and {@link #PROPAGATION_NESTED} can cause
 * that, it usually doesn't make sense to specify those settings in other cases.
 * Furthermore, be aware that not all transaction managers will support those
 * advanced features and thus might throw corresponding exceptions when given
 * non-default values.
 *
 * <p>The {@link #isReadOnly() read-only flag} applies to any transaction context,
 * whether backed by an actual resource transaction or operating non-transactionally
 * at the resource level. In the latter case, the flag will only apply to managed
 * resources within the application, such as a Hibernate <code>Session</code>.
 *
 * @author Juergen Hoeller
 * @since 08.05.2003
 * @see PlatformTransactionManager#getTransaction(TransactionDefinition)
 * @see org.springframework.transaction.support.DefaultTransactionDefinition
 * @see org.springframework.transaction.interceptor.TransactionAttribute
 */
public interface TransactionDefinition {

  /**
   * Support a current transaction; create a new one if none exists.
   * Analogous to the EJB transaction attribute of the same name.
   * <p>This is typically the default setting of a transaction definition,
   * and typically defines a transaction synchronization scope.
   */
  int PROPAGATION_REQUIRED = 0;

  /**
   * Support a current transaction; execute non-transactionally if none exists.
   * Analogous to the EJB transaction attribute of the same name.
   * <p><b>NOTE:</b> For transaction managers with transaction synchronization,
   * <code>PROPAGATION_SUPPORTS</code> is slightly different from no transaction
   * at all, as it defines a transaction scope that synchronization might apply to.
   * As a consequence, the same resources (a JDBC <code>Connection</code>, a
   * Hibernate <code>Session</code>, etc) will be shared for the entire specified
   * scope. Note that the exact behavior depends on the actual synchronization
   * configuration of the transaction manager!
   * <p>In general, use <code>PROPAGATION_SUPPORTS</code> with care! In particular, do
   * not rely on <code>PROPAGATION_REQUIRED</code> or <code>PROPAGATION_REQUIRES_NEW</code>
   * <i>within</i> a <code>PROPAGATION_SUPPORTS</code> scope (which may lead to
   * synchronization conflicts at runtime). If such nesting is unavoidable, make sure
   * to configure your transaction manager appropriately (typically switching to
   * "synchronization on actual transaction").
   * @see org.springframework.transaction.support.AbstractPlatformTransactionManager#setTransactionSynchronization
   * @see org.springframework.transaction.support.AbstractPlatformTransactionManager#SYNCHRONIZATION_ON_ACTUAL_TRANSACTION
   */
  int PROPAGATION_SUPPORTS = 1;

  /**
   * Support a current transaction; throw an exception if no current transaction
   * exists. Analogous to the EJB transaction attribute of the same name.
   * <p>Note that transaction synchronization within a <code>PROPAGATION_MANDATORY</code>
   * scope will always be driven by the surrounding transaction.
   */
  int PROPAGATION_MANDATORY = 2;

  /**
   * Create a new transaction, suspending the current transaction if one exists.
   * Analogous to the EJB transaction attribute of the same name.
   * <p><b>NOTE:</b> Actual transaction suspension will not work out-of-the-box
   * on all transaction managers. This in particular applies to
   * {@link org.springframework.transaction.jta.JtaTransactionManager},
   * which requires the <code>javax.transaction.TransactionManager</code>
   * to be made available it to it (which is server-specific in standard J2EE).
   * <p>A <code>PROPAGATION_REQUIRES_NEW</code> scope always defines its own
   * transaction synchronizations. Existing synchronizations will be suspended
   * and resumed appropriately.
   * @see org.springframework.transaction.jta.JtaTransactionManager#setTransactionManager
   */
  int PROPAGATION_REQUIRES_NEW = 3;

  /**
   * Do not support a current transaction; rather always execute non-transactionally.
   * Analogous to the EJB transaction attribute of the same name.
   * <p><b>NOTE:</b> Actual transaction suspension will not work out-of-the-box
   * on all transaction managers. This in particular applies to
   * {@link org.springframework.transaction.jta.JtaTransactionManager},
   * which requires the <code>javax.transaction.TransactionManager</code>
   * to be made available it to it (which is server-specific in standard J2EE).
   * <p>Note that transaction synchronization is <i>not</i> available within a
   * <code>PROPAGATION_NOT_SUPPORTED</code> scope. Existing synchronizations
   * will be suspended and resumed appropriately.
   * @see org.springframework.transaction.jta.JtaTransactionManager#setTransactionManager
   */
  int PROPAGATION_NOT_SUPPORTED = 4;

  /**
   * Do not support a current transaction; throw an exception if a current transaction
   * exists. Analogous to the EJB transaction attribute of the same name.
   * <p>Note that transaction synchronization is <i>not</i> available within a
   * <code>PROPAGATION_NEVER</code> scope.
   */
  int PROPAGATION_NEVER = 5;

  /**
   * Execute within a nested transaction if a current transaction exists,
   * behave like {@link #PROPAGATION_REQUIRED} else. There is no analogous
   * feature in EJB.
   * <p><b>NOTE:</b> Actual creation of a nested transaction will only work on
   * specific transaction managers. Out of the box, this only applies to the JDBC
   * {@link org.springframework.jdbc.datasource.DataSourceTransactionManager}
   * when working on a JDBC 3.0 driver. Some JTA providers might support
   * nested transactions as well.
   * @see org.springframework.jdbc.datasource.DataSourceTransactionManager
   */
  int PROPAGATION_NESTED = 6;


  /**
   * Use the default isolation level of the underlying datastore.
   * All other levels correspond to the JDBC isolation levels.
   * @see java.sql.Connection
   */
  int ISOLATION_DEFAULT = -1;

  /**
   * Indicates that dirty reads, non-repeatable reads and phantom reads
   * can occur.
   * <p>This level allows a row changed by one transaction to be read by another
   * transaction before any changes in that row have been committed (a "dirty read").
   * If any of the changes are rolled back, the second transaction will have
   * retrieved an invalid row.
   * @see java.sql.Connection#TRANSACTION_READ_UNCOMMITTED
   */
  int ISOLATION_READ_UNCOMMITTED = Connection.TRANSACTION_READ_UNCOMMITTED;

  /**
   * Indicates that dirty reads are prevented; non-repeatable reads and
   * phantom reads can occur.
   * <p>This level only prohibits a transaction from reading a row
   * with uncommitted changes in it.
   * @see java.sql.Connection#TRANSACTION_READ_COMMITTED
   */
  int ISOLATION_READ_COMMITTED = Connection.TRANSACTION_READ_COMMITTED;

  /**
   * Indicates that dirty reads and non-repeatable reads are prevented;
   * phantom reads can occur.
   * <p>This level prohibits a transaction from reading a row with uncommitted changes
   * in it, and it also prohibits the situation where one transaction reads a row,
   * a second transaction alters the row, and the first transaction re-reads the row,
   * getting different values the second time (a "non-repeatable read").
   * @see java.sql.Connection#TRANSACTION_REPEATABLE_READ
   */
  int ISOLATION_REPEATABLE_READ = Connection.TRANSACTION_REPEATABLE_READ;

  /**
   * Indicates that dirty reads, non-repeatable reads and phantom reads
   * are prevented.
   * <p>This level includes the prohibitions in {@link #ISOLATION_REPEATABLE_READ}
   * and further prohibits the situation where one transaction reads all rows that
   * satisfy a <code>WHERE</code> condition, a second transaction inserts a row
   * that satisfies that <code>WHERE</code> condition, and the first transaction
   * re-reads for the same condition, retrieving the additional "phantom" row
   * in the second read.
   * @see java.sql.Connection#TRANSACTION_SERIALIZABLE
   */
  int ISOLATION_SERIALIZABLE = Connection.TRANSACTION_SERIALIZABLE;


  /**
   * Use the default timeout of the underlying transaction system,
   * or none if timeouts are not supported. 
   */
  int TIMEOUT_DEFAULT = -1;


  /**
   * Return the propagation behavior.
   * <p>Must return one of the <code>PROPAGATION_XXX</code> constants
   * defined on {@link TransactionDefinition this interface}.
   * @return the propagation behavior
   * @see #PROPAGATION_REQUIRED
   * @see org.springframework.transaction.support.TransactionSynchronizationManager#isActualTransactionActive()
   */
  int getPropagationBehavior();

  /**
   * Return the isolation level.
   * <p>Must return one of the <code>ISOLATION_XXX</code> constants
   * defined on {@link TransactionDefinition this interface}.
   * <p>Only makes sense in combination with {@link #PROPAGATION_REQUIRED}
   * or {@link #PROPAGATION_REQUIRES_NEW}.
   * <p>Note that a transaction manager that does not support custom isolation levels
   * will throw an exception when given any other level than {@link #ISOLATION_DEFAULT}.
   * @return the isolation level
   */
  int getIsolationLevel();

  /**
   * Return the transaction timeout.
   * <p>Must return a number of seconds, or {@link #TIMEOUT_DEFAULT}.
   * <p>Only makes sense in combination with {@link #PROPAGATION_REQUIRED}
   * or {@link #PROPAGATION_REQUIRES_NEW}.
   * <p>Note that a transaction manager that does not support timeouts will throw
   * an exception when given any other timeout than {@link #TIMEOUT_DEFAULT}.
   * @return the transaction timeout
   */
  int getTimeout();

  /**
   * Return whether to optimize as a read-only transaction.
   * <p>The read-only flag applies to any transaction context, whether
   * backed by an actual resource transaction
   * ({@link #PROPAGATION_REQUIRED}/{@link #PROPAGATION_REQUIRES_NEW}) or
   * operating non-transactionally at the resource level
   * ({@link #PROPAGATION_SUPPORTS}). In the latter case, the flag will
   * only apply to managed resources within the application, such as a
   * Hibernate <code>Session</code>.
   * <p>This just serves as a hint for the actual transaction subsystem;
   * it will <i>not necessarily</i> cause failure of write access attempts.
   * A transaction manager which cannot interpret the read-only hint will
   * <i>not</i> throw an exception when asked for a read-only transaction.
   * @return <code>true</code> if the transaction is to be optimized as read-only 
   * @see org.springframework.transaction.support.TransactionSynchronization#beforeCommit(boolean)
   * @see org.springframework.transaction.support.TransactionSynchronizationManager#isCurrentTransactionReadOnly()
   */
  boolean isReadOnly();

  /**
   * Return the name of this transaction. Can be <code>null</code>.
   * <p>This will be used as the transaction name to be shown in a
   * transaction monitor, if applicable (for example, WebLogic's).
   * <p>In case of Spring's declarative transactions, the exposed name will be
   * the <code>fully-qualified class name + "." + method name</code> (by default).
   * @return the name of this transaction
   * @see org.springframework.transaction.interceptor.TransactionAspectSupport
   * @see org.springframework.transaction.support.TransactionSynchronizationManager#getCurrentTransactionName()
   */
  String getName();

}

 

還是覺得不安心,發兩張圖證明隔離級別和傳播機制:

  • eclipse中給出的關於傳播機制的智能提示截圖
  • eclipse中給出的關於隔離級別的智能提示截圖

 


免責聲明!

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



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