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

背景:

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

       insert into   data_cache ( customerID,organizationID,createTime)
              ( 
                      select   customerID,organizationID,createTime
                        from   data
                       where   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,createTime
                        from   data
                       where   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 

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

posted on 2018-10-19 11:15  Mrlw  阅读(6639)  评论(0编辑  收藏  举报

导航