背景

最近在排查问题时发现,偶尔会发生关于数据库锁超时的现象,会发生像如下的报错信息:

Exception in thread "pool-3-thread-1" org.springframework.dao.CannotAcquireLockException:
### Error updating database. Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLTransactionRollbackException: Lock wait timeout exceeded; try restarting transaction
### The error may involve com.zr.center.mybatis.auto.mapper.UserMapper.updateByExampleSelective-Inline
### The error occurred while setting parameters
### SQL: update user SET user_name = ? WHERE ( user_id = ? )
### Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLTransactionRollbackException: Lock wait timeout exceeded; try restarting transaction
; ]; Lock wait timeout exceeded; try restarting transaction; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLTransactionRollbackException: Lock wait timeout exceeded; try restarting transaction
at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.doTranslate(SQLErrorCodeSQLExceptionTranslator.java:262)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:72)
at org.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible(MyBatisExceptionTranslator.java:75)
at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:447)
at com.sun.proxy.$Proxy101.update(Unknown Source)
at org.mybatis.spring.SqlSessionTemplate.update(SqlSessionTemplate.java:295)
at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:59)
at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:53)
at com.sun.proxy.$Proxy103.updateByExampleSelective(Unknown Source)
at com.zr.center.framework.web.service.BaseService.updateByExampleSelective(BaseService.java:97)
at com.zr.center.api.test.service.TestService.updateUserName(TestService.java:34)
at com.zr.center.api.test.service.TestService$$FastClassBySpringCGLIB$$bd3aa32.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:746)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:294)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688)
at com.zr.center.api.test.service.TestService$$EnhancerBySpringCGLIB$$59b19302.updateUserName(<generated>)
at com.zr.center.ApplicationTests.lambda$testTxLockWaiting$0(ApplicationTests.java:32)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLTransactionRollbackException: Lock wait timeout exceeded; try restarting transaction
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
at com.mysql.jdbc.Util.getInstance(Util.java:408)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:952)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3976)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3912)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2530)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2683)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2486)

排查

经过排查,DBA给出的日志中并未有死锁,死锁的原因排除,查询业务日志发现在高并发的时期有时会有重复请求过来,也有一个服务在处理某个逻辑时会发一条mq消息,而同时会消费这条消息,此时也会导致锁超时。超时原因就是因为一个事务中处理的逻辑过多,有调外部服务(超时),有更新其它多张表的操作,这样就会导致后面事务请求超时,报以上错误。

重现步骤

  • 数据库配置

关于配置信息查看,可以看到事务隔离是RR,事务锁等待时长为默认的50s



  • 事务代码

/**
* @description: 用户服务超时测试
* @author: chong guo
* @create: 2018-12-10 14:44
*/
@Service
@Slf4j
public class TestService extends BaseService<User, UserExample, Long> { /**
* 更新用户名称
*
* @param userId
* @param name
*/
@Transactional(rollbackFor = Exception.class)
public void updateUserName(Long userId, String name) throws InterruptedException {
log.info("开始更新用户名【{}】,用户ID为【{}】", name, userId);
UserExample userExample = new UserExample();
userExample.createCriteria().andUserIdEqualTo(userId); User user = new User();
user.setUserName(name); super.updateByExampleSelective(user, userExample); // 模拟业务超时,有可能调用外部远程服务超时,也有可能处理其它逻辑
Thread.sleep(55000);
log.info("结束更新用户名【{}】,用户ID为【{}】", name, userId); } }
  • 模拟并发

/**
* @author Chong Guo
*/
@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
public class ApplicationTests {
@Resource
TestService testService; private final int threadCount = 5; @Test
public void testTxLockWaiting() throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(threadCount); ExecutorService threadPool = Executors.newFixedThreadPool(300);
for (int i = 0; i < threadCount; i++) {
threadPool.execute(() -> {
try {
testService.updateUserName(611526166943105024L, "chongguo");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
countDownLatch.countDown();
} });
}
countDownLatch.await();
threadPool.shutdown();
log.info("Test tx lock is over");
Thread.sleep(100000);
}
}

运行代码后会现三次失败,二次成功,失败原因都是锁超时

总结

  1. 代码优化,将大事务中无关的逻辑拆出来,异步处理
  2. 业务提供方涉及到外部调用的接口需要把超时时长设置短一些
  3. 如果调用方有重试机制,可以针对业务去掉重试,将connetion time设置大一些

Lock wait timeout exceeded?代码该优化了的更多相关文章

  1. SQL性能优化常见措施(Lock wait timeout exceeded)

    SQL性能优化常见措施 目 录 1.mysql中explain命令使用 2.mysql中mysqldumpslow的使用 3.mysql中修改my.ini配置文件记录日志 4.mysql中如何加索引 ...

  2. mysql_提示 Lock wait timeout exceeded解决办法

    我的mysql报这个错 err=1205 - Lock wait timeout exceeded; try restarting transaction 利用 SHOW PROCESSLIST来查看 ...

  3. MySQL事务锁等待超时 Lock wait timeout exceeded; try restarting transaction

    工作中处理定时任务分发消息时出现的问题,在查找并解决问题的时候,将相关的问题博客收集整理,在此记录下,以便之后再遇到相同的问题,方便查阅. 问题场景 问题出现的场景: 在消息队列处理消息时,同一事务内 ...

  4. mysql死锁,等待资源,事务锁,Lock wait timeout exceeded; try restarting transaction解决

    前面已经了解了InnoDB关于在出现锁等待的时候,会根据参数innodb_lock_wait_timeout的配置,判断是否需要进行timeout的操作,本文档介绍在出现锁等待时候的查看及分析处理: ...

  5. 排查mysql innodb Lock wait timeout exceeded; try restarting transaction的问题

    OMG写的时候崩溃了一次. 触发关注这个问题的事情是 我们在使用pt-online-schedule 改表的时候总是拿不到锁,并且报出mysql innodb Lock wait timeout ex ...

  6. com.mysql.jdbc.exceptions.jdbc4.MySQLTransactionRollbackException: Lock wait timeout exceeded; try restarting transaction

    本文为博主原创: 以下为在程序运行过程中报的错误, org.springframework.dao.CannotAcquireLockException: ### Error updating dat ...

  7. mysql Lock wait timeout exceeded; try restarting transaction解决

    前面已经了解了InnoDB关于在出现锁等待的时候,会根据参数innodb_lock_wait_timeout的配置,判断是否需要进行timeout的操作,本文档介绍在出现锁等待时候的查看及分析处理: ...

  8. java.sql.SQLException: Lock wait timeout exceeded; try restarting transaction

    java.sql.SQLException: Lock wait timeout exceeded; try restarting transaction问题 1.问题描述 执行了几条update语句 ...

  9. Mysql错误: ERROR 1205: Lock wait timeout exceeded解决办法(MySQL锁表、事物锁表的处理方法)

    Java执行一个SQL查询未提交,遇到1205错误. java.lang.Exception: ### Error updating database.  Cause: java.sql.SQLExc ...

随机推荐

  1. 做一个logitic分类之鸢尾花数据集的分类

    做一个logitic分类之鸢尾花数据集的分类 Iris 鸢尾花数据集是一个经典数据集,在统计学习和机器学习领域都经常被用作示例.数据集内包含 3 类共 150 条记录,每类各 50 个数据,每条记录都 ...

  2. PTA A1013

    第七天 A1013 Battle Over Cities (25 分) 题目内容 It is vitally important to have all the cities connected by ...

  3. webstorm中关闭烦人Eslint语法检查

    打开许久没打开的webstrom,以前关闭的配置不知道怎么又乱了,react项目到处报错,真是没法忍. 关闭eslint位置:File-->Setting-->Languages& ...

  4. Pandas对缺失值的处理

    Pandas使用这些函数处理缺失值: isnull和notnull:检测是否是空值,可用于df和series dropna:丢弃.删除缺失值 axis : 删除行还是列,{0 or 'index', ...

  5. 如何判断前后端bug

    测试工程师不只是负责发现问题,除了发现问题这种基本功外,定位问题,提出解决方案,提出预防方案也是要掌握的技能.这里先说定位问题的要求,定位问题要向深入,前提当然是对功能.产品的流程.开发方案.开发人员 ...

  6. Unity项目 - DeathtrapDungeon死亡地牢

    目录 游戏原型 项目演示 绘图资源 代码实现 注意事项 技术探讨 参考来源 游戏原型 死亡地牢是一款 2D-Roguelike 的地牢冒险游戏.手握利刃,斩杀怪物,在凶险的地牢内生存下去.但注意,敌人 ...

  7. 安装centos8

    一.     镜像下载 国内源下载镜像:(推荐) http://mirrors.aliyun.com/centos/8.0.1905/isos/x86_64/CentOS-8-x86_64-1905- ...

  8. Flask基础(13)-->Flask扩展Flask-Script

    Flask基础(12)-->Flask扩展Flask-Script # 前提是安装了Flask-Script # 联网运行 pip install flask-script from flask ...

  9. 利用Python与selenium自动化模拟登陆12306官网!

    近年来,12306的反爬越来越来严重,从一年前的 获取tk参数后到现在增加了 JS.CSS等加密方式! 目前大部分人利用的登陆方式都是利用selenium ,此文也不例外. 环境:        Wi ...

  10. .Net Core 商城微服务项目系列(八):购物车

    最近加班有点多,一周五天,四天加班到11点+,心很累.原因是我当前在的这个组比较特殊,相当于业务的架构组,要为其它的开发组提供服务和监控.所以最近更新的也少,不过这个元旦三天假应该会更新三篇. 这篇是 ...