Why do developers have to understand database locks?

1. Lock?

1.1 What is a lock

The meaning of a lock in reality is: a closed object, opened with a key or a password. Locks in computers are generally used to manage concurrent access to shared resources. For example, Lock and synchronized, which are familiar to our java students, are our common locks. Of course, there are locks in our database to control concurrent access to resources, which is one of the differences between a database and a file system.

1.2 Why do you need to understand database locks?

Generally speaking, for ordinary developers, it is enough to know some DQL (select), DML (insert, update, delete) when using the database.

Xiao Ming is a Java development engineer who has just graduated and works in an Internet company. His usual job is to fulfill the requirements of PM. Of course, he cannot escape the framework of spring, springmvc, and mybatis while fulfilling the requirements, so generally speaking, sql is still his own. Handwritten, encounter more complex SQL will go to Baidu from the Internet. For some more important operations, such as transactions, Xiaoming will use spring transactions to manage database transactions. Due to the relatively small amount of data, distributed transactions are currently not involved.

A few months ago, Xiaoming had a good time. I knew that one day, Xiaoming received a request. The merchant has a configuration item called a discount configuration item. You can configure rules such as buy one get one free, buy one get two free and so on. Of course, these configurations It is transmitted to the backend in batches, so there is a problem that each rule has to match whether he deletes, adds or modifies, so the backend logic is more troublesome. The smart Xiaoming thought of a way to delete the configuration of this merchant directly. , and then add them all. Xiao Ming completed the development immediately and went online successfully.

There is nothing wrong with going online, but some mysql-insert-deadlock exceptions often appear in the log. Because Xiao Ming's experience is relatively infrequent, this is the first time that I met this type of question, so I asked the old driver of their group - Dahong, when Dahong saw this question, and after reading his code, he outputted a few commands and read a few A log, immediately located the problem, and told Xiao Ming: This is because a gap lock is added when deleting, but the gap locks are compatible, but when inserting new data, it will be blocked by the gap lock due to the insertion intention lock. , causing both parties to be occupied by each other's resources, resulting in a deadlock. After listening to it, Xiao Ming seemed to understand, but because there were so many things about Dahong, it was inconvenient to trouble Dahong all the time, so he decided to come down and think for himself. After get off work, Xiao Ming recalled what Dahong said, what is a gap lock and what is an insertion intention lock. It seems that as a developer, you should not only write SQL for the database, otherwise, you will not be able to solve some intractable diseases. After thinking about it, Xiao Ming embarked on the road of no return to learn Mysql lock.

2.InnoDB

2.1mysql architecture

Xiao Ming did not rush to unlock this knowledge. He first learned about the Mysql architecture: it can be found that Mysql consists of connection pool components, management services and tool components, sql interface components, query analyzer components, optimizer components, and buffer components. , a plug-in storage engine, and physical files.

Xiao Ming found that the storage engine in MySQL is provided as a plug-in. There are many storage engines in MySQL, and each storage engine has its own characteristics. Then Xiao Ming typed in the command line:

show engines \G;

At first glance, there are so many kinds of engines.

Then type the following command to view the default engine of the current database:

show variables like '%storage_engine%';

Xiao Ming suddenly realized: It turned out that his database was InnoDB, and he vaguely remembered that when he was in school, he seemed to have heard of an engine called MyIsAM. Xiao Ming thought what was the difference between the two? Immediately searched for the information:

Contrast InnoDB MyIsAM
affairs support not support
Lock Support MVCC row lock table lock
foreign key support not support
storage The storage space is large due to the need for cache compressible
Applicable scene There is a certain amount of update and Insert lots of choices

Xiaoming has a general understanding of the difference between InnoDB and MyIsAM. Since InnoDB is used, Xiaoming does not have too much entanglement.

2.2 Isolation of transactions

Before Xiao Ming studied locks, he recalled the database transaction isolation that he taught in school before. In fact, one of the functions of locks in the database is to achieve transaction isolation. The isolation of transactions is actually used to solve problems such as dirty reads, non-repeatable reads, and phantom reads.

2.2.1 Dirty reads

One transaction reads uncommitted updates to another transaction. What does that mean?

time point Transaction A Transaction B
1 begin;
2 select * from user where id = 1; begin;
3 update user set namm = 'test' where id = 1;
4 select * from user where id = 1;
5 commit; commit;

In transactions A and B, transaction A queries the data with id=1 in the user table at time points 2 and 4, respectively, but transaction B is modified at time point 3, resulting in the query of transaction A in 4. The result is actually modified by transaction B. Broken isolation in the database.

2.2.2 Non-repeatable read

In the same transaction, reading the same data multiple times returns different results. Unlike dirty reading, what is read here is after it has been committed.

time point Transaction A Transaction B
1 begin;
2 select * from user where id = 1; begin;
3 update user set namm = 'test' where id = 1;
4 commit;
5 select * from user where id = 1;
6 commit;
The operation committed in transaction B is before the second query of transaction A, but the update result of transaction B is still read, which also destroys the isolation of the transaction.

2.2.3 Phantom reading

A transaction reads the committed insert data of another transaction.

time point Transaction A Transaction B
1 begin;
2 select * from user where id > 1; begin;
3 insert user select 2;
4 commit;
5 select * from user where id > 1;
6 commit;

In transaction A, the id greater than 1 is queried twice, and there is no data in the first query result with id greater than 1, but because transaction B inserted a piece of data with id=2, transaction A can find it in the second query Data inserted in transaction B.

Isolation in Transactions:

isolation level dirty read non-repeatable read hallucinations
Read Uncommitted (RUC) NO NO NO
Read Committed (RC) YES NO NO
Repeatable Read (RR) YES YES NO
Serializable YES YES YES

Xiaoming noticed that in the process of collecting data, some data was written to InnoDB which is a bit different from other databases. InnoDB's repeatable read can actually solve phantom reads. Xiaoming thought: This InnoDB is pretty cool, I have to take a good look at it. See what the principle is.

2.3 InnoDB lock types

Xiao Ming first understand what are the common lock types in Mysql:

2.3.1 S or X

Two standard row-level locks are implemented in InnoDb, which can be simply viewed as two read-write locks:

  • S-共享锁:又叫读锁,其他事务可以继续加共享锁,但是不能继续加排他锁。
  • X-排他锁: 又叫写锁,一旦加了写锁之后,其他事务就不能加锁了。

兼容性:是指事务A获得一个某行某种锁之后,事务B同样的在这个行上尝试获取某种锁,如果能立即获取,则称锁兼容,反之叫冲突。

纵轴是代表已有的锁,横轴是代表尝试获取的锁。

. X S
X 冲突 冲突
S 冲突 兼容

2.3.2 意向锁

意向锁在InnoDB中是表级锁,和他的名字一样他是用来表达一个事务想要获取什么。意向锁分为:

  • 意向共享锁:表达一个事务想要获取一张表中某几行的共享锁。
  • 意向排他锁:表达一个事务想要获取一张表中某几行的排他锁。

这个锁有什么用呢?为什么需要这个锁呢? 首先说一下如果没有这个锁,如果要给这个表加上表锁,一般的做法是去遍历每一行看看他是否有行锁,这样的话效率太低,而我们有意向锁,只需要判断是否有意向锁即可,不需要再去一行行的去扫描。

在InnoDB中由于支持的是行级的锁,因此InnboDB锁的兼容性可以扩展如下:

. IX IS X S
IX 兼容 兼容 冲突 冲突
IS 兼容 兼容 冲突 兼容
X 冲突 冲突 冲突 冲突
S 冲突 兼容 冲突 兼容

2.3.3 自增长锁

自增长锁是一种特殊的表锁机制,提升并发插入性能。对于这个锁有几个特点:

  • 在sql执行完就释放锁,并不是事务执行完。
  • 对于Insert...select大数据量插入会影响插入性能,因为会阻塞另外一个事务执行。
  • 自增算法可以配置。

在MySQL5.1.2版本之后,有了很多优化,可以根据不同的模式来进行调整自增加锁的方式。小明看到了这里打开了自己的MySQL发现是5.7之后,于是便输入了下面的语句,获取到当前锁的模式:

mysql> show variables like 'innodb_autoinc_lock_mode';
+--------------------------+-------+
| Variable_name            | Value |
+--------------------------+-------+
| innodb_autoinc_lock_mode | 2     |
+--------------------------+-------+
1 row in set (0.01 sec)

在MySQL中innodb_autoinc_lock_mode有3种配置模式:0、1、2,分别对应”传统模式”, “连续模式”, “交错模式”。

  1. 传统模式:也就是我们最上面的使用表锁。
  2. 连续模式:对于插入的时候可以确定行数的使用互斥量,对于不能确定行数的使用表锁的模式。
  3. 交错模式:所有的都使用互斥量,为什么叫交错模式呢,有可能在批量插入时自增值不是连续的,当然一般来说如果不看重自增值连续一般选择这个模式,性能是最好的。

2.4InnoDB锁算法

小明已经了解到了在InnoDB中有哪些锁类型,但是如何去使用这些锁,还是得靠锁算法。

2.4.1 记录锁(Record-Lock)

记录锁是锁住记录的,这里要说明的是这里锁住的是索引记录,而不是我们真正的数据记录。

  • 如果锁的是非主键索引,会在自己的索引上面加锁之后然后再去主键上面加锁锁住.
  • 如果没有表上没有索引(包括没有主键),则会使用隐藏的主键索引进行加锁。
  • 如果要锁的列没有索引,则会进行全表记录加锁。

2.4.2 间隙锁

间隙锁顾名思义锁间隙,不锁记录。锁间隙的意思就是锁定某一个范围,间隙锁又叫gap锁,其不会阻塞其他的gap锁,但是会阻塞插入间隙锁,这也是用来防止幻读的关键。

2.4.3 next-key锁

这个锁本质是记录锁加上gap锁。在RR隔离级别下(InnoDB默认),Innodb对于行的扫描锁定都是使用此算法,但是如果查询扫描中有唯一索引会退化成只使用记录锁。为什么呢? 因为唯一索引能确定行数,而其他索引不能确定行数,有可能在其他事务中会再次添加这个索引的数据会造成幻读。

这里也说明了为什么Mysql可以在RR级别下解决幻读。

2.4.4 插入意向锁

插入意向锁Mysql官方对其的解释:

An insert intention lock is a type of gap lock set by INSERT operations prior to row insertion. This lock signals the intent to insert in such a way that multiple transactions inserting into the same index gap need not wait for each other if they are not inserting at the same position within the gap. Suppose that there are index records with values of 4 and 7. Separate transactions that attempt to insert values of 5 and 6, respectively, each lock the gap between 4 and 7 with insert intention locks prior to obtaining the exclusive lock on the inserted row, but do not block each other because the rows are nonconflicting.

可以看出插入意向锁是在插入的时候产生的,在多个事务同时写入不同数据至同一索引间隙的时候,并不需要等待其他事务完成,不会发生锁等待。假设有一个记录索引包含键值4和7,不同的事务分别插入5和6,每个事务都会产生一个加在4-7之间的插入意向锁,获取在插入行上的排它锁,但是不会被互相锁住,因为数据行并不冲突。

这里要说明的是如果有间隙锁了,插入意向锁会被阻塞。

2.5 MVCC

MVCC,多版本并发控制技术。在InnoDB中,在每一行记录的后面增加两个隐藏列,记录创建版本号和删除版本号。通过版本号和行锁,从而提高数据库系统并发性能。

在MVCC中,对于读操作可以分为两种读:

  • 快照读:读取的历史数据,简单的select语句,不加锁,MVCC实现可重复读,使用的是MVCC机制读取undo中的已经提交的数据。所以它的读取是非阻塞的。
  • 当前读:需要加锁的语句,update,insert,delete,select...for update等等都是当前读。

在RR隔离级别下的快照读,不是以begin事务开始的时间点作为snapshot建立时间点,而是以第一条select语句的时间点作为snapshot建立的时间点。以后的select都会读取当前时间点的快照值。

在RC隔离级别下每次快照读均会创建新的快照。

具体的原理是通过每行会有两个隐藏的字段一个是用来记录当前事务,一个是用来记录回滚的指向Undolog。利用undolog就可以读取到之前的快照,不需要单独开辟空间记录。

3.加锁分析

小明到这里,已经学习很多mysql锁有关的基础知识,所以决定自己创建一个表搞下实验。首先创建了一个简单的用户表:

CREATE TABLE `user` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(11) CHARACTER SET utf8mb4 DEFAULT NULL,
  `comment` varchar(11) CHARACTER SET utf8 DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `index_name` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;

然后插入了几条实验数据:

insert user select 20,333,333;
insert user select 25,555,555;
insert user select 20,999,999;

数据库事务隔离选择了RR

3.1 实验1

小明开启了两个事务,进行实验1.

时间点 事务A 事务B
1 begin;
2 select * from user where name = '555' for update; begin;
3 insert user select 31,'556','556';
4 ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction

小明开启了两个事务并输入了上面的语句,发现事务B居然出现了超时,小明看了一下自己明明是对name = 555这一行进行的加锁,为什么我想插入name=556给我阻塞了。于是小明打开命令行输入:

select * from information_schema.INNODB_LOCKS

发现在事务A中给555加了Next-key锁,事务B插入的时候会首先进行插入意向锁的插入,于是得出下面结论: 可以看见事务B由于间隙锁和插入意向锁的冲突,导致了阻塞。

3.2 实验2

小明发现上面查询条件用的是普通的非唯一索引,于是小明就试了一下主键索引:

时间点 事务A 事务B
1 begin;
2 select * from user where id = 25 for update; begin;
3 insert user select 26,'666','666';
4 Query OK, 1 row affected (0.00 sec)
Records: 1 Duplicates: 0 Warnings: 0

居然发现事务B并没有发生阻塞,哎这个是咋回事呢,小明有点疑惑,按照实验1的套路应该会被阻塞啊,因为25-30之间会有间隙锁。于是小明又祭出了命令行,发现只加了X记录锁。原来是因为唯一索引会降级记录锁,这么做的理由是:非唯一索引加next-key锁由于不能确定明确的行数有可能其他事务在你查询的过程中,再次添加这个索引的数据,导致隔离性遭到破坏,也就是幻读。唯一索引由于明确了唯一的数据行,所以不需要添加间隙锁解决幻读。

3.3 实验3

上面测试了主键索引,非唯一索引,这里还有个字段是没有索引,如果对其加锁会出现什么呢?

时间点 事务A 事务B
1 begin;
2 select * from user where comment = '555' for update; begin;
3 insert user select 26,'666','666';
4 ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction
5 insert user select 31,'3131','3131';
6 ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction
7 insert user select 10,'100','100';
8 ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction
小明一看哎哟我去,这个咋回事呢,咋不管是用实验1非间隙锁范围的数据,还是用间隙锁里面的数据都不行,难道是加了表锁吗?

的确,如果用没有索引的数据,其会对所有聚簇索引上都加上next-key锁。

所以大家平常开发的时候如果对查询条件没有索引的,一定进行一致性读,也就是加锁读,会导致全表加上索引,会导致其他事务全部阻塞,数据库基本会处于不可用状态。

4.回到事故

4.1 死锁

小明做完实验之后总算是了解清楚了加锁的一些基本套路,但是之前线上出现的死锁又是什么东西呢?

死锁:是指两个或两个以上的事务在执行过程中,因争夺资源而造成的一种互相等待的现象。说明有等待才会有死锁,解决死锁可以通过去掉等待,比如回滚事务。

解决死锁的两个办法:

  1. 等待超时:当某一个事务等待超时之后回滚该事务,另外一个事务就可以执行了,但是这样做效率较低,会出现等待时间,还有个问题是如果这个事务所占的权重较大,已经更新了很多数据了,但是被回滚了,就会导致资源浪费。
  2. 等待图(wait-for-graph): 等待图用来描述事务之间的等待关系,当这个图如果出现回路如下:

就出现回滚,通常来说InnoDB会选择回滚权重较小的事务,也就是undo较小的事务。

4.2 线上问题

小明到这里,基本需要的基本功都有了,于是在自己的本地表中开始复现这个问题:

时间点 事务A 事务B
1 begin; begin;
2 delete from user where name = '777'; delete from user where name = '666';
3 insert user select 27,'777','777'; insert user select 26,'666','666';
4 ERROR 1213 (40001): Deadlock found when trying to get lock; try restarting transaction Query OK, 1 row affected (14.32 sec) Records: 1 Duplicates: 0 Warnings: 0

可以看见事务A出现被回滚了,而事务B成功执行。 具体每个时间点发生了什么呢?

时间点2:事务A删除name = '777'的数据,需要对777这个索引加上next-Key锁,但是其不存在,所以只对555-999之间加间隙锁,同理事务B也对555-999之间加间隙锁。间隙锁之间是兼容的。

时间点3:事务A,执行Insert操作,首先插入意向锁,但是555-999之间有间隙锁,由于插入意向锁和间隙锁冲突,事务A阻塞,等待事务B释放间隙锁。事务B同理,等待事务A释放间隙锁。于是出现了A->B,B->A回路等待。

时间点4:事务管理器选择回滚事务A,事务B插入操作执行成功。

4.3 修复BUG

这个问题总算是被小明找到了,就是因为间隙锁,现在需要解决这个问题,这个问题的原因是出现了间隙锁,那就来去掉他吧:

  • 方案一:隔离级别降级为RC,在RC级别下不会加入间隙锁,所以就不会出现毛病了,但是在RC级别下会出现幻读,可提交读都破坏隔离性的毛病,所以这个方案不行。
  • 方案二:隔离级别升级为可序列化,小明经过测试后发现不会出现这个问题,但是在可序列化级别下,性能会较低,会出现较多的锁等待,同样的也不考虑。
  • 方案三:修改代码逻辑,不要直接删,改成每个数据由业务逻辑去判断哪些是更新,哪些是删除,那些是添加,这个工作量稍大,小明写这个直接删除的逻辑就是为了不做这些复杂的事的,所以这个方案先不考虑。
  • 方案四:较少的修改代码逻辑,在删除之前,可以通过快照查询(不加锁),如果查询没有结果,则直接插入,如果有通过主键进行删除,在之前第三节实验2中,通过唯一索引会降级为记录锁,所以不存在间隙锁。

经过考虑小明选择了第四种,马上进行了修复,然后上线观察验证,发现现在已经不会出现这个Bug了,这下小明总算能睡个安稳觉了。

4.4 如何防止死锁

小明通过基础的学习和平常的经验总结了如下几点:

  • 以固定的顺序访问表和行。交叉访问更容易造成事务等待回路。
  • 尽量避免大事务,占有的资源锁越多,越容易出现死锁。建议拆成小事务。
  • 降低隔离级别。如果业务允许(上面4.3也分析了,某些业务并不能允许),将隔离级别调低也是较好的选择,比如将隔离级别从RR调整为RC,可以避免掉很多因为gap锁造成的死锁。
  • 为表添加合理的索引。防止没有索引出现表锁,出现的死锁的概率会突增。

最后

由于篇幅有限很多东西并不能介绍全如果感兴趣的同学可以阅读《Mysql技术内幕-InnoDB引擎》第6章 以及 何大师的MySQL 加锁处理分析。作者本人水平有限,如果有什么错误,还请指正。

最后这篇文章被我收录于JGrowing,一个全面,优秀,由社区一起共建的Java学习路线,如果您想参与开源项目的维护,可以一起共建,github地址为:https://github.com/javagrowing/JGrowing 麻烦给个小星星哟。

如果你觉得这篇文章对你有文章,可以关注我的技术公众号,你的关注和转发是对我最大的支持,O(∩_∩)O

{{o.name}}
{{m.name}}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324144209&siteId=291194637