MYSQL-GAP&插入意向锁 死锁记录

1、建表:

CREATE TABLE `test_dead_lock` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键id',
  `user_id` bigint(20) unsigned NOT NULL COMMENT 用户id',
  `user_name` varchar(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '用户名',
`type` int(10) DEFAULT '0' COMMENT '类型',
  PRIMARY KEY (`id`),
  UNIQUE KEY `unique_idx` (`user_id`,`user_name`),
  KEY `idx_name` (`user_name`)

) ENGINE=InnoDB  DEFAULT CHARSET=utf8mb4 COMMENT='测试死锁表';

mysql 5.7,事务隔离级别RR,会话自动提交事务关闭【set autocommit=off;】

2、数据准备

INSERT INTO `test_dead_lock` (`id`, `user_id`, `user_name`, `type`)
VALUES
	(1,1,'name22',0),
	(2,2,'name22',0),
	(3,3,'name3',0),
	(4,4,'name22',0),
	(9,8,'name8',0),
	(12,10,'name10',0),
	(41,10,'name100',0),
	(64,11,'name11A',0),
	(65,12,'name12A',0);

3、事务处理

事务1 事务2 备  注
start transaction;
start transaction;

delete from test_dead_lock

where user_id=5 ;

不存在数据,加间隙锁

delete from test_dead_lock

where user_id=6 ;

不存在数据,加间隙锁

insert ignore into test_dead_lock

(user_id,user_name)
values

(5,'name5A'),(5,'name5AA');

加插入意向锁,等待2事务间隙锁释放

insert ignore into test_dead_lock

(user_id,user_name)
values

(6,'name6A'),(6,'name6AA');

加插入意向锁,等待1事务间隙锁释放

死锁

rollback; rollback;

备注:也可以直接 delete 13,14,插入13,14数据来验证,间隙锁范围是正无穷。

4、死锁日志

show engine innodb status;

5、涉及知识点:

 (1)mysql 事务隔离级别

(2)mysql 锁

你可能感兴趣的:(数据库,mysql,数据库,servlet)