小编给大家分享一下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中如何排查并发插入引起的死锁问题”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注创新互联行业资讯频道!