线上出现MySQL死锁报警,经过show engine innodb status命令查看死锁日志,结合异常代码,还原发生死锁的事务场景以下:html
环境: mysql5.7,事务隔离级别REPEATABLE-READmysql
表结构sql
CREATE TABLE `ta` ( `id` int AUTO_INCREMENT, `a` int, `b` int , `c` int , PRIMARY KEY (`id`), UNIQUE KEY `ux_a_b` (`a`,`b`) ) ENGINE=InnoDB 数据: mysql> select * from ta; +----+------+------+------+ | id | a | b | c | +----+------+------+------+ | 1 | 1 | 10 | 100 | | 2 | 3 | 20 | 99 | | 3 | 5 | 50 | 80 | +----+------+------+------+
并发事务并发
T1 | T2 |
---|---|
begin; | begin |
delete from ta where a = 4;//ok, 0 rows affected | |
delete from ta where a = 4; //ok, 0 rows affected | |
insert into ta(a,b,c) values(4, 11, 3),(4, 2, 5);//wating,被阻塞 | |
insert into ta(a,b,c) values(4, 11, 3),(4, 2, 5); //ERROR 1213 (40001): Deadlock found when trying to get lock; | |
T1执行完成, 2 rows affected |
从上面能够看出,并发事务都成功执行delete后(影响行数为0),执行insert出现死锁。分布式
查看死锁日志,显示事务T1的insert语句在等待插入意向锁,lock_mode X locks gap before rec insert intention waiting
;事务T2持有a=4的gap lock,同时也在等待插入意向锁。另外,T1能执行delete,说明它也拿到了gap lock,因此,两个事务都持有gap lock,致使循环等待插入意向锁而发生死锁。spa
锁兼容矩阵:.net
方案以下几种选择:日志
insert加锁分析,参考文章http://www.aneasystone.com/archives/2017/12/solving-dead-locks-three.htmlcode