前提條件,percona 5.6版本,事務(wù)隔離級別為RR
mysql> show create table test_autoinc_lock/G*************************** 1. row *************************** Table: test_autoinc_lockCreate Table: CREATE TABLE `test_autoinc_lock` ( `id` int(11) NOT NULL AUTO_INCREMENT, `a` int(11) DEFAULT NULL, PRIMARY KEY (`id`), KEY `idx_a` (`a`)) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf81 row in set (0.00 sec)mysql> select * from test_autoinc_lock;+----+------+| id | a |+----+------+| 1 | 1 || 12 | 2 || 2 | 3 || 3 | 5 || 4 | 7 || 5 | 7 || 6 | 9 || 7 | 10 |+----+------+8 rows in set (0.00 sec) |
條件1 innodb_autoinc_lock_mode設(shè)置為0
session1 begin;delete from test_autoinc_lock where a>7;//這時(shí)未提交session2mysql> insert into test_autoinc_lock(a) values(100);//gap鎖的存在,這時(shí)處于鎖等待session3mysql> insert into test_autoinc_lock(a) values(2);//這時(shí)同樣處于等待狀態(tài),理論上這個(gè)不是gap鎖的鎖定范圍,那么它是在等什么呢session4mysql> select * from information_schema.innodb_trx/G*************************** 1. row *************************** trx_id: 2317 trx_state: LOCK WAIT trx_started: 2016-10-31 19:28:05 trx_requested_lock_id: 2317:20 trx_wait_started: 2016-10-31 19:28:05 trx_weight: 1 trx_mysql_thread_id: 9 trx_query: insert into test_autoinc_lock(a) values(2) trx_operation_state: setting auto-inc lock trx_tables_in_use: 1 trx_tables_locked: 1 trx_lock_structs: 1 trx_lock_memory_bytes: 360 trx_rows_locked: 0 trx_rows_modified: 0 trx_concurrency_tickets: 0 trx_isolation_level: REPEATABLE READ trx_unique_checks: 1 trx_foreign_key_checks: 1trx_last_foreign_key_error: NULL trx_adaptive_hash_latched: 0 trx_adaptive_hash_timeout: 10000 trx_is_read_only: 0trx_autocommit_non_locking: 0 |
這時(shí)查看session3是等待自增鎖,一直處于setting auto-inc lock狀態(tài)
session2
ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction
這時(shí)session3鎖等待超時(shí)退出
session3
這時(shí)再看session3可以發(fā)現(xiàn)insert完成。
mysql> select * from test_autoinc_lock;+----+------+| id | a |+----+------+| 1 | 1 || 12 | 2 || 13 | 2 || 2 | 3 || 3 | 5 || 4 | 7 || 5 | 7 || 6 | 9 || 7 | 10 |+----+------+9 rows in set (0.00 sec)//注意看這時(shí)的最大自增值是13,也就是之前自增最大值上+1,也就是說session2后來釋放了預(yù)計(jì)生成的自增id,將13留給了session3,自增id值的申請完全是串行順序的。 |
結(jié)論:innodb_autoinc_lock_mode為0時(shí)的,也就是官方說的traditional
級別,該自增鎖是表鎖級別,且必須等待當(dāng)前SQL執(zhí)行完成后或者回滾掉才會(huì)釋放,這樣在高并發(fā)的情況下可想而知自增鎖競爭是比較大的。
新聞熱點(diǎn)
疑難解答
圖片精選