背景:
有一張表須要天天定時遷移數據,採用的SQL以下(表名已調整)html
insert into data_cache ( customerID,organizationID,createTime) ( select customerID,organizationID,createTime from data where DATE(createTime) <= DATE(?) and autoIndex >= ? and autoIndex <= ? )
大致意思是根據autoIndex去斷定那些數據須要遷移,在程序中已經分好區域了mysql
好比1~100,101~200,201~300.spring
表結構以下:sql
兩張表的數據表結構均一致,如:數據庫
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字段,取消自增以及非空。重試正常。spa
問題根源:
其實真正的問題涉及到Mysql對自增的設計。
詳情能夠參閱:
https://www.cnblogs.com/JiangLe/p/6362770.html
大致就是數據庫的模式對這種自增插入有3種設置。原有的環境以及生產爲2,更新後改成1致使的。
能夠輸入如下命令查看設置:
show global variables
innodb_autoinc_lock_mode 2
由於咱們對連續沒什麼要求,因此採用性能最好的便可