如下,表 table_a 字段 id (主键),check_no(varchar 唯一索引),no_type 三个字段,这个表只有 insert 操作,没有查询,其他操作,数据量 1000 万左右
另外一个表 table_b 数据量 1 万左右
逻辑是这样:
1.insert table_a valus(主键,单号,单号状态);
2.步骤 1 插入成功之后 select * table_b from where id = xx for update;然后对这个表 update table_b set xxx=xxx where id =xx
并发不大,每秒 10 个请求,一般情况没有任何问题,16ms 左右就可以执行完,但是偶尔会有死锁(频率不大,一两个月会有发生一次,时间没有规律,持续时长 短的话 30s,长的话 5 分钟)
异常日志表现如下:
1.项目日志报错:
SQL: select * from tables_b where id=xxx for update
Cause: java.sql.SQLException: Lock wait timeout exceeded; try restarting transaction
; SQL []; Lock wait timeout exceeded; try restarting transaction; nested exception is java.sql.SQLException:
Lock wait timeout exceeded; try restarting transaction
2.数据库慢查询如下:
Time: 190413 0:01:45
Thread_id: 27063157 Schema: m_center QC_hit: No
Query_time: 12.579884 Lock_time: 10.984690 Rows_sent: 0 Rows_examined: 0
SET timestamp=1555128105;
INSERT INTO table_a(id,check_no,no_type) VALUES
('xxxx','xxxxx','xxx');
3.监控数据库状态
cpu 消耗升高,内存消耗升高,有死锁(数据库配置:8H8G)
分析测试:
1.开始怀疑并发操作单条记录会造成死锁,然后自己并发测试 10 个线程对同一条记录进行修改,每个线程 100 次循环,测试结果并未发生死锁
2.数据库慢查询日志锁时间很长的都是 table_a,如上图 Lock_time: 10.984690,不明白为什么 insert 表会 lock 这么久
小弟知识有限,请各位大佬指点迷津