小编给大家分享一下mysql中如何排查并发插入引起的死锁问题,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!
挂着VPN排查问题,不过当时并没有排查出原因
上班之后,发现是客户端的一个bug.本来应该发送一个请求,但是却发送了大量的请求,应用层面又没有做幂等设计,所以所有的请求都落到了数据库层面。
数据库是一个过程
环境
MySQL 5.6.14
事务隔离级别 读提交
引起问题的逻辑大致如下:
CREATE TABLE t1 (i INT, PRIMARY KEY (i)) ENGINE = InnoDB;
Now suppose that three sessions perform the following operations in order:
Session 1:
START TRANSACTION;
INSERT INTO t1 VALUES(1);
Session 2:
START TRANSACTION;
INSERT INTO t1 VALUES(1);
Session 3:
START TRANSACTION;
INSERT INTO t1 VALUES(1);
Session 1:
ROLLBACK;
The first operation by session 1 acquires an exclusive lock for the row. The operations by sessions 2 and 3 both result in a duplicate-key error and they both request a shared lock for the row. When session 1 rolls back, it releases its exclusive lock on the row and the queued shared lock requests for sessions 2 and 3 are granted. At this point, sessions 2 and 3 deadlock: Neither can acquire an exclusive lock for the row because of the shared lock held by the other.
A similar situation occurs if the table already contains a row with key value 1 and three sessions perform the following operations in order:
Session 1:
START TRANSACTION;
DELETE FROM t1 WHERE i = 1;
Session 2:
START TRANSACTION;
INSERT INTO t1 VALUES(1);
Session 3:
START TRANSACTION;
INSERT INTO t1 VALUES(1);
Session 1:
COMMIT;
The first operation by session 1 acquires an exclusive lock for the row. The operations by sessions 2 and 3 both result in a duplicate-key error and they both request a shared lock for the row. When session 1 commits, it releases its exclusive lock on the row and the queued shared lock requests for sessions 2 and 3 are granted. At this point, sessions 2 and 3 deadlock: Neither can acquire an exclusive lock for the row because of the shared lock held by the other.
可以看到,Insert的时候,对记录上排它锁和插入意向锁.
并发的情况下,如果这个记录已经上了排它锁,则会尝试给这个记录上共享锁.
如果有三个以上的并发线程,
第一个线程上了排它锁,第二和第三个线程,看到该记录有排他锁,则尝试给这个记录上共享锁。
一旦第一个线程回滚,则第二,第三线程拥有共享锁的同时,都在申请排它锁.这时候就出现了死锁.
需要注意的是,假如第一个线程提交了,则第二个,第三个线程会报重复主键的错误,但是这时候,第二个,第三个线程,还是拥有这个记录的共享锁.第二,第三线程必须回滚.否则他们拥有的共享锁不释放.
回到最开始的问题.
三个线程同时insert award_free_firecracker_watch_common表,一个线程成功获取排它锁,其他两个线程上共享锁.
等获取排他锁的线程提交,两个上共享锁的线程,最后一步 update award_free_firecracker_watch_common表,则产生了死锁。
他们都是在获取了共享锁的同时,申请排它锁.
以上是“mysql中如何排查并发插入引起的死锁问题”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!