Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

初步理解 MySQL InnoDB 的 gap 鎖與 next-key 鎖

編輯:關於 Android 開發

初步理解 MySQL InnoDB 的 gap 鎖與 next-key 鎖

初識 InnoDB 的 gap 鎖,感覺這個設計頗為獨特,與其他數據庫的做法不太一樣,於是整理一份簡短的筆記。關於 gap 鎖的資料已經很多,這裡主要是把要點與自己的驗證過程留下來。

1. 什麼是 gap

官方術語表的定義是:

A place in an InnoDB index data structure where new values could be inserted.

說白了,gap 就是索引樹裡可以插入新記錄的空隙。相應地,gap lock 就是加在這個空隙上的鎖;還有一種 next-key lock,是「記錄本身 + 這條記錄前面的 gap」的組合鎖。

2. gap 鎖與 next-key 鎖的作用

MySQL 文檔寫得很清楚:

To prevent phantoms, InnoDB uses an algorithm called next-key locking that combines
index-row locking with gap locking. InnoDB performs row-level locking in such a way
that when it searches or scans a table index, it sets shared or exclusive locks on the
index records it encounters. Thus, the row-level locks are actually index-record locks.
In addition, a next-key lock on an index record also affects the "gap" before that index
record. That is, a next-key lock is an index-record lock plus a gap lock on the gap
preceding the index record. If one session has a shared or exclusive lock on record R in
an index, another session cannot insert a new index record in the gap immediately before
R in the index order.

核心就一句:防止幻讀。通過鎖住區間來阻止符合特定條件的新記錄被插入,因為插入時也需要獲取 gap 鎖(Insert Intention Locks)。

3. 什麼時候會加 gap 鎖

這與事務隔離級別直接相關,只有在 REPEATABLE READ 及以上的隔離級別下、特定操作才會取 gap 鎖或 next-key lock。

文檔在 REPEATABLE READ 一節中說:

For locking reads (SELECT with FOR UPDATE or LOCK IN SHARE MODE), UPDATE, and DELETE
statements, locking depends on whether the statement uses a unique index with a unique
search condition, or a range-type search condition. For a unique index with a unique
search condition, InnoDB locks only the index record found, not the gap before it. For
other search conditions, InnoDB locks the index range scanned, using gap locks or
next-key locks to block insertions by other sessions into the gaps covered by the range.

換句話說:locking read、UPDATE、DELETE 時,除了「唯一索引 + 唯一搜索條件」這種情況只鎖命中的那一條記錄,其餘都會獲取 gap 鎖或 next-key 鎖,把它掃過的整個範圍鎖住。

動手驗證。先建一張非唯一索引的表:

mysql> show create table tb2\G
Table: tb2
Create Table: CREATE TABLE `tb2` (
  `id` int(11) DEFAULT NULL,
  `c1` int(11) DEFAULT NULL,
  KEY `tb2_idx1` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4

表裡三條記錄,id 分別是 10、20、30:

mysql> select * from tb2;
+------+------+
| id   | c1   |
+------+------+
|   10 |    0 |
|   20 |    0 |
|   30 |    0 |
+------+------+

會話 1:更新 id=20 但不提交。

mysql> begin;
mysql> update tb2 set c1=2 where id=20;
Query OK, 1 row affected (0.04 sec)

會話 2:逐個嘗試插入,結果很能說明問題。

mysql> begin;
mysql> insert into tb2 values(9,4);
Query OK, 1 row affected (0.00 sec)

mysql> insert into tb2 values(10,4);
ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction

mysql> insert into tb2 values(19,4);
ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction

mysql> insert into tb2 values(20,4);
ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction

mysql> insert into tb2 values(21,4);
ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction

mysql> insert into tb2 values(29,4);
ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction

mysql> insert into tb2 values(30,4);
Query OK, 1 row affected (0.01 sec)

結論一目了然:[10, 30) 這個區間被鎖住了,10 插不進去,30 卻可以。這正是 next-key lock 的邊界語義——鎖的是記錄 R 之前的 gap,而不包含 R 之後的空間。

再看更新操作:

mysql> update tb2 set c1=4 where id=10;
Query OK, 0 rows affected
mysql> update tb2 set c1=4 where id=20;
ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction
mysql> update tb2 set c1=4 where id=30;
Query OK, 0 rows affected

只有 id=20 這條記錄被卡住,另外兩條暢通無阻——因為 UPDATE 走的是記錄鎖,不會去申請 gap 鎖。

還有一個重要前提:如果會話 1 的 UPDATE 沒有命中索引(導致全表掃描),那麼 gap 或 next-key 鎖覆蓋的範圍就是整張表,任何值都插不進來。這是線上故障裡相當常見的一類——忘記在 where 條件列上建索引,一條 UPDATE 就把整張表鎖死了。

READ COMMITTED 下的行為完全不同:

For locking reads (SELECT with FOR UPDATE or LOCK IN SHARE MODE), UPDATE statements, and
DELETE statements, InnoDB locks only index records, not the gaps before them, and thus
permits the free insertion of new records next to locked records.

只鎖已有記錄,不加 gap 鎖,因此無法阻止幻讀,但並發寫入能力更好。

SERIALIZABLE 則是:

This level is like REPEATABLE READ, but InnoDB implicitly converts all plain SELECT
statements to SELECT ... LOCK IN SHARE MODE if autocommit is disabled.

與 RR 的主要區別在於,autocommit 關閉時會把普通 SELECT 隱式轉成 LOCK IN SHARE MODE,也就是連普通查詢都會獲取 gap 鎖或 next-key 鎖。

4. REPEATABLE READ 與幻讀

在 consistent read(一致性讀)場景下,RR 看到的是事務啟動時建立的快照,別的事務即使插入了新行通常也看不到,所以多數情況下幻讀不會出現。

但 locking read、UPDATE、DELETE 走的是當前讀,它們會看到已提交的修改,包括新插入的行。文檔也建議:若想得到數據庫的「最新」狀態,應使用 READ COMMITTED 或 locking read。

看個例子。

會話 1:

mysql> START TRANSACTION;
mysql> select id,c1 from tb1 where id=1;
+----+------+
| id | c1   |
+----+------+
|  1 |  100 |
+----+------+

會話 2:

mysql> update tb1 set c1=101 where id=1;
Query OK, 1 row affected (0.03 sec)

回到會話 1:

mysql> select id,c1 from tb1 where id=1 LOCK IN SHARE MODE;
|  1 |  101 |   ← 加鎖讀,看到了新值

mysql> select id,c1 from tb1 where id=1;
|  1 |  100 |   ← 普通讀,仍是快照

mysql> update tb1 set c1=c1+1000 where id=1;
Query OK, 1 row affected

mysql> select id,c1 from tb1 where id=1;
|  1 | 1101 |   ← 更新後,連普通讀也看到了新值

最後那次 UPDATE 的行為嚴格說違背了 RR 的直覺承諾:它是基於 101 而不是 100 去加 1000 的,等於看到了事務啟動後其他事務的並發修改。這一點在應用開發中要特別小心,別假設「RR 的事務裡讀到的數據不會變」。有意思的是,其他一些數據庫在類似場景下通常會直接報錯。

5. 其他值得注意的差異

RR 與 RC 還有一個重要區別:RC 下掃描過但不匹配的記錄不會加鎖,或者先加鎖後立刻釋放,即 semi-consistent read;而 RR 下掃過的記錄都要加鎖。這個差異在涉及全表掃描的更新場景裡影響極大,可能讓一條本該很快的語句變成阻塞全表的元兇。

關於 InnoDB 的加鎖處理細節,何登成的那篇《MySQL 加鎖處理分析》講得非常透徹,推薦一讀。

6. 參考資料

  • MySQL 5.7 Reference Manual:InnoDB Locking Reads、InnoDB Transaction Isolation Levels、InnoDB Consistent Nonlocking Reads
  • 何登成《MySQL 加鎖處理分析》
  • 《MySQL 行鎖、表鎖、gap 鎖相關整理》等相關博文

總結一句:gap 鎖是 InnoDB 為了在 RR 級別下兼顧「可重複讀」與「防幻讀」而付出的代價,代價就是插入並發在鎖定區間內被犧牲。理解它的邊界條件——有沒有走索引、鎖的是哪個區間、隔離級別是什麼——基本就能解釋線上絕大多數與鎖等待相關的現象。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved