欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 运维知识 > 数据库 >内容正文

数据库

Mysql自增列,并发插入时导致死锁的问题

发布时间:2024/9/20 数据库 40 豆豆
生活随笔 收集整理的这篇文章主要介绍了 Mysql自增列,并发插入时导致死锁的问题 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

背景:

  有一张表需要每天定时迁移数据,采用的SQL如下(表名已调整)

insert into data_cache ( customerID,organizationID,createTime)( select customerID,organizationID,createTimefrom datawhere DATE(createTime) <= DATE(?)and autoIndex >= ? and autoIndex <= ?)

大体意思是根据autoIndex去判定那些数据需要迁移,在程序中已经分好区域了

比如1~100,101~200,201~300.

表结构如下:

两张表的数据表结构均一致,如:

CREATE TABLE `data` (`customerID` varchar(50) NOT NULL COMMENT '客户编号',`organizationID` varchar(50) DEFAULT NULL COMMENT '机构号',`createTime` timestamp NULL DEFAULT current_timestamp() COMMENT '创建时间',`lastModifiedDatetime` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp() COMMENT '最近修改时间',`autoIndex` int(11) NOT NULL AUTO_INCREMENT COMMENT '索引',`modifyDate` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp() COMMENT '修改日期',PRIMARY KEY (`customerID`),KEY `autoIndex` (`autoIndex`) USING BTREE) ENGINE=InnoDB AUTO_INCREMENT=468 DEFAULT CHARSET=utf8

之前测试环境,甚至生产环境都是正常的代码,最近更新了数据库,出现了死锁异常如下:

insert into data_cache ( customerID,organizationID,createTime)( select customerID,organizationID,createTimefrom datawhere DATE(createTime) <= DATE(?)and autoIndex >= ? and autoIndex <= ?)

Deadlock found when trying to get lock; try restarting transaction; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLTransactionRollbackException: Deadlock found when trying to get lock; try restarting transaction

    org.springframework.dao.DeadlockLoserDataAccessException: PreparedStatementCallback; 

问题:

    Mysql插入居然报了死锁,还是两条插入并发,在数据源没有交集的情况下,并且之前一直是正常。百思不得其解

尝试解决:

    移除掉缓存表中的autoIndex字段,取消自增以及非空。重试正常。

问题根源:

    其实真正的问题涉及到Mysql对自增的设计。

  详情可以参阅:

  https://www.cnblogs.com/JiangLe/p/6362770.html

  大体就是数据库的模式对这种自增插入有3种设置。原有的环境以及生产为2,更新后改为1导致的。

可以输入以下命令查看设置:

show global variables

innodb_autoinc_lock_mode 2 

因为我们对连续没什么要求,所以采用性能最好的即可

来源:https://www.cnblogs.com/liangwen/p/9815336.html

总结

以上是生活随笔为你收集整理的Mysql自增列,并发插入时导致死锁的问题的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。