githubhtml
什麼是本地事務(Local Transaction)?本地事務也稱爲數據庫事務或傳統事務(相對於分佈式事務而言)。它的執行模式就是常見的:java
本地事務有這麼幾個特徵:git
在討論事務時,咱們繞不過一組概念:ACID,咱們來看看Wiki是怎麼解釋ACID的:github
Atomicity requires that each transaction be "all or nothing": if one part of the transaction fails, then the entire transaction fails, and the database state is left unchanged. An atomic system must guarantee atomicity in each and every situation, including power failures, errors and crashes. To the outside world, a committed transaction appears (by its effects on the database) to be indivisible ("atomic"), and an aborted transaction does not happen.
關鍵詞在於:數據庫
The consistency property ensures that any transaction will bring the database from one valid state to another. Any data written to the database must be valid according to all defined rules, including constraints, cascades, triggers, and any combination thereof. This does not guarantee correctness of the transaction in all ways the application programmer might have wanted (that is the responsibility of application-level code), but merely that any programming errors cannot result in the violation of any defined rules.
一致性要求任何寫到數據庫的數據都必須知足於預先定義的規則(好比餘額不能小於0、外鍵約束等),簡單來講就是在任什麼時候間點都不能出現違反一致性要求的狀態。併發
The isolation property ensures that the concurrent execution of transactions results in a system state that would be obtained if transactions were executed sequentially, i.e., one after the other. Providing isolation is the main goal of concurrency control. Depending on the concurrency control method (i.e., if it uses strict - as opposed to relaxed - serializability), the effects of an incomplete transaction might not even be visible to another transaction.
隔離性要求若是兩個事務修改同一個數據,則必須按順序執行,而且前一個事務若是未完成,那麼未完成的中間狀態對另外一個事務不可見。oracle
The durability property ensures that once a transaction has been committed, it will remain so, even in the event of power loss, crashes, or errors. In a relational database, for instance, once a group of SQL statements execute, the results need to be stored permanently (even if the database crashes immediately thereafter). To defend against power loss, transactions (or their effects) must be recorded in a non-volatile memory.
持久性的關鍵在於一旦「完成提交」(committed),那麼數據就不會丟失。app
在提到隔離性的時候咱們提到,在修改同一份數據的狀況下,兩個事務必須挨個執行以避免出現衝突狀況。而數據庫有四種隔離級別(注意:不是全部數據庫支持全部隔離級別)分佈式
Isolation Level | Dirty Reads | Non-Repeatable Reads | Phantom Reads |
---|---|---|---|
Read uncommitted | 容許 | 容許 | 容許 |
Read committed | 不容許 | 容許 | 容許 |
Repeatable reads | 不容許 | 不容許 | 容許 |
Serializable | 不容許 | 不容許 | 不容許 |
PS. 大多數數據庫的默認隔離級別是Read committed。ide
來複習一下Dirty reads、Non-repeatable reads、Phantom reads的概念:
SELECT ... WHERE
獲得一些行,B事務插入新行或者更新已有的行使得這些行知足A事務的WHERE
條件,A事務再次SELECT ... WHERE
結果比上一次多了一些行。大多數數據庫在實現以上事務隔離級別(Read uncommitted除外)時採用的機制是鎖。這也就是爲何常常說當應用程序裏大量使用事務或者高併發狀況下會出現性能低下、死鎖的問題。