性能测试,使用Jmeter进行测试。今天遇到并发情况下的死锁问题,经排查是A线程进行批量插入,B线程进行单条纪录插入,性能测试100并发。
在可重复读或以上隔离级别下的特定操作会取得gap lock 或 next-key lock,在Select、Update和Delete时,除了基于唯一索引的查询之外,其它索引查询时都会获取gap lock 或 next-key lock,即锁住其扫描的范围。主键索引也属于唯一索引,所以主键索引是不会使用gap lock 或next-key lock。
A、B线程调用的是不同的接口,但是会操作同一张表。查看测试结果、发现有部分线程接口返回失败。
mysql 的行锁是针对索引加的锁,不是针对记录加的锁,所以虽然是访问不同行的记录,但如果是使用相同的索引键,是会出现锁冲突的,设计时要注意。
例如:t_product_inner_indentifier 表中ref_id字段有索引,product_name字段没有索引:
将事务设为手动提交,默认隔离级别
sessionA | sessionB |
SET autocommit=0; | SET autocommit=0; |
SELECT * FROM t_product_inner_indentifier WHERE ref_id = 14 AND product_name='AA' FOR UPDATE; ref_id id product_name ref 14 2 AA 1 | |
会话B与会话A访问的是不同的记录,但是因为使用了 相同的索引值,所以需要等待锁 SELECT * FROM t_product_inner_indentifier WHERE ref_id = 14 AND product_name='BB' FOR UPDATE; 等待... |
当表有多个索引时候,不同的事务可以使用不同的索引锁定不同的行,无论什么索引,innodb都会使用行锁来对数据加锁。
RR深入理解
A | B |
SET autocommit=0; | SET autocommit=0; |
A:开启事务 B:(开启事务)读取数据
A:修改数据(不提交事务) B:读取数据 (同一纪录)
A:提交事务 B:读取数据 (同一纪录)
B:修改数据(在A修改的基础上修改),提交事务
1、事务A执行select 4 for update获取(4,+oo )间隙锁
2、图中B事务再执行select 5 for update获取( 5,+co )的间隙锁
3、事务A执行insert 4发现事务A自己持有(4,+oo)间隙锁,所以不用等待呀!
4、事务B执行insert 5发现事务A没有commit,持有(4,+ oo )间隙锁,所以等待事务A释放锁5、事务A提交,事务B insert 5获取到锁,commit
===>在3的insert操作中,会去获取插入意向锁,而插入意向锁也是一种gap锁,根据矩阵图,插入意向锁和gap间隙锁是冲突的,所以insert操作需要等待间隙锁的释放。
Error updating database. Cause: com.mysql.cj.jdbc.exceptions.MySQLTransactionRollbackException: Deadlock found when trying to get lock; try restarting transaction ### The error may exist in file [D:\iot\target\classes\mapper\business\products\ProductPropertiesMapper.xml] ### The error may involve com.iot.module.business.products.properties.dao.ProductPropertiesDao.insertBatch-Inline ### The error occurred while setting parameters ### SQL: INSERT INTO t_product_properties( product_id, identifier, name, description, access, original_required, update_required, custom, data_type, specs, default_value, ref_id, create_time, update_time ) VALUES( ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )
Cause: com.mysql.cj.jdbc.exceptions.MySQLTransactionRollbackException: Deadlock found when trying to get lock; try restarting transaction;
{msg":"运行时异常:org.springframework.dao.DeadlockLoserDataAccessException:
### Error updating database. Cause: com.mysql.cj.jdbc.exceptions.MySQLTransactionRollbackException: Deadlock found when trying to get lock; try restarting transaction\r\n### The error may exist in com/iot/module/business/products/events/basic/dao/ProductEventsDao.java (best guess)\r\n### The error may involve com.iot.module.business.products.events.basic.dao.ProductEventsDao.insert-Inline\r\n### The error occurred while setting parameters\r\n### SQL: INSERT INTO t_product_events ( product_id, identifier, name, description, type, original_required, update_required, custom, method, level ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )\r\n### Cause: com.mysql.cj.jdbc.exceptions.MySQLTransactionRollbackException: Deadlock found when trying to get lock; try restarting transaction\n;