MySQL报Lock wait timeout exceeded; try restarting transaction

背景

有个定时任务特别耗时,涉及到了一个表,此时平台页面触发一个该表的操作,请求卡顿了几十秒,最后返回了一个500异常。

报错

java 复制代码
### Error updating database.  Cause: com.mysql.cj.jdbc.exceptions.MySQLTransactionRollbackException: Lock wait timeout exceeded; try restarting transaction
### The error may exist in com/xxx/xxx/xxx/xxxMapper.java (best guess)
### The error may involve com.xxx.xxx.xxx.xxxMapper.update-Inline
### The error occurred while setting parameters
### SQL: UPDATE table  SET update_time=?,task_status=?    WHERE  delete_flag=0  AND (id = ? AND task_status <= ?)
### Cause: com.mysql.cj.jdbc.exceptions.MySQLTransactionRollbackException: Lock wait timeout exceeded; try restarting transaction
; Lock wait timeout exceeded; try restarting transaction; nested exception is com.mysql.cj.jdbc.exceptions.MySQLTransactionRollbackException: Lock wait timeout exceeded; try restarting transaction

解决

问题的关键是多个线程来竞争同一把锁导致的,InnoDB的锁默认等待时间innodb_lock_wait_timeout=50秒,如何避免一个线程拿到锁的时间太长便是我们的重中之重。

  • 修改innodb_lock_wait_timeout的值,无疑是杯水车薪,治标不治本。
  • 先根据报错日志找到这两条SQL语句的具体操作,分析是否有耗时现象,是否存在长事务问题(加了@Transactional,我这块就是这个原因导致的)。
  • 或者执行show engine innodb status,查看是否有锁等待/死锁信息,都可以找到是哪条SQL导致的。
  • 如果还不行,就需要适当优化索引了,宗旨就是减少SQL语句的执行时间。
相关推荐
高溪流29 分钟前
3.数据库表的基本操作
数据库·mysql
alonewolf_9938 分钟前
深入剖析MySQL锁机制与MVCC原理:高并发场景下的数据库核心优化
数据库·mysql
一 乐1 小时前
绿色农产品销售|基于springboot + vue绿色农产品销售系统(源码+数据库+文档)
java·前端·数据库·vue.js·spring boot·后端·宠物
黄宝康1 小时前
sqlyog密钥亲测有效
mysql
Codeking__1 小时前
Redis初识——什么是Redis
数据库·redis·mybatis
YIN_尹1 小时前
【MySQL】数据类型(上)
android·mysql·adb
k***1951 小时前
Spring 核心技术解析【纯干货版】- Ⅶ:Spring 切面编程模块 Spring-Instrument 模块精讲
前端·数据库·spring
程序员黄老师1 小时前
主流向量数据库全面解析
数据库·大模型·向量·rag
Full Stack Developme2 小时前
Redis 可以实现哪些业务功能
数据库·redis·缓存
rgeshfgreh2 小时前
Spring事务传播机制深度解析
java·前端·数据库