1. 程式人生 > >Mysql事物鎖等待超時 Lock wait timeout exceeded; try restarting transaction

Mysql事物鎖等待超時 Lock wait timeout exceeded; try restarting transaction

工作中同事遇到此異常,查詢解決問題時,收集整理形成此篇文章。

問題場景

問題出現環境:
1、在同一事務內先後對同一條資料進行插入和更新操作;
2、多臺伺服器操作同一資料庫;
3、瞬時出現高並發現象;

不斷的有一下異常丟擲,異常資訊:

org.springframework.dao.CannotAcquireLockException: 
### Error updating database.  Cause: java.sql.SQLException: Lock wait timeout exceeded; try restarting transaction
### The error may involve com.*.dao.mapper.PhoneFlowMapper.updateByPrimaryKeySelective-Inline
### The error occurred while setting parameters ### SQL:-----後面為SQL語句及堆疊資訊--------

原因分析

在高併發的情況下,Spring事物造成資料庫死鎖,後續操作超時丟擲異常。
Mysql資料庫採用InnoDB模式,預設引數:innodb_lock_wait_timeout設定鎖等待的時間是50s,一旦資料庫鎖超過這個時間就會報錯。

解決方案

1、通過下面語句查詢到為提交事務的資料,kill掉此執行緒即可。

select * from information_schema.innodb_trx

2、增加鎖等待時間,即增大下面配置項引數值,單位為秒(s)

innodb_lock_wait_timeout=500

3、優化儲存過程,事務避免過長時間的等待。

參考資訊

1、鎖等待超時。是當前事務在等待其它事務釋放鎖資源造成的。可以找出鎖資源競爭的表和語句,優化SQL,建立索引等。如果還是不行,可以適當減少併發執行緒數。
2、事務在等待給某個表加鎖時超時,估計是表正被另的程序鎖住一直沒有釋放。
可以用 SHOW INNODB STATUS/G; 看一下鎖的情況。
3、搜尋解決之道,在管理節點的[ndbd default]區加:
TransactionDeadLockDetectionTimeOut=10000(設定 為10秒)預設是1200(1.2秒)
4、InnoDB會自動的檢測死鎖進行回滾,或者終止死鎖的情況。

InnoDB automatically detects transaction deadlocks and rolls back a transaction or transactions to break the deadlock. InnoDB tries to pick small transactions to roll back, where the size of a transaction is determined by the number of rows inserted, updated, or deleted.

如果引數innodb_table_locks=1並且autocommit=0時,InnoDB會留意表的死鎖,和MySQL層面的行級鎖。另外,InnoDB不會檢測MySQL的Lock Tables命令和其他儲存引擎死鎖。你應該設定innodb_lock_wait_timeout來解決這種情況。
innodb_lock_wait_timeout是Innodb放棄行級鎖的超時時間。

深入研究

由於此專案採用Spring+mybatis框架,事物控制採用“org.springframework.jdbc.datasource.DataSourceTransactionManager”類進行處理。此處還需進行進一步調研Spring實現的機制。