预警风暴:从数据库冲突到行锁的智慧解围
场景:当设备检测到预警时,它会调用预警接口一次性上传多个预警数据。
一、日志告警
在欣赏自己优雅的代码和系统日志的时,发现了error错误。嗯?哪个小子改了我的代码。
### Error updating database. Cause: java.sql.SQLIntegrityConstraintViolationException: Duplicate entry 'b83943f8cda89809e8b5724f' for key 'alert_record.PRIMARY'
### The error may exist in com/hengli/ca/mvc/record/mapper/AlertRecordMapper.java (best guess)
### The error may involve com.hengli.ca.mvc.record.mapper.AlertRecordMapper.insert-Inline
### The error occurred while setting parameters
### SQL: INSERT INTO alert_record ( id, warn_id, warn_type, begin_time, date_time, dict, scene, scene_name, version, device, device_name, info, event_id, ori_event, warning, detail, update_time ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )
### Cause: java.sql.SQLIntegrityConstraintViolationException: Duplicate entry 'b83943f8cda89809e8b5724f' for key 'alert_record.PRIMARY'
; Duplicate entry 'b83943f8cda89809e8b5724f' for key 'alert_record.PRIMARY'; nested exception is java.sql.SQLIntegrityConstraintViolationException: Duplicate entry 'b83943f8cda89809e8b5724f' for key 'alert_record.PRIMARY'
我记得有加同步锁的,怎么会出现这样的错误呢?查看代码。
private synchronized AlertRecord getRecord(AlertRecord record) {
// 因为一级缓存导致,第一次
// AlertRecord alertRecord = alertRecordService.getByIdNoCache(record.getId());
AlertRecord alertRecord = alertRecordService.getById(record.getId());
// 新增修改预警
if (alertRecord != null) {
alertRecordService.updateById(record);
} else {
alertRecordService.save(record);
}
return alertRecord;
}
没问题啊,这里已经加了同步锁synchronized,同一时间只会有一个线程执行这段代码,先查再新增修改。不应该出现上述问题才对。
二、本地复现
本地性能测试也复现了同样的问题,不知道该怎么解决,但好在是复现了。
三、寻求帮助
寻求了一个和尚的帮忙,他怀疑是mybatis的一级缓存导致的,我也是顺着这个方式去查了,一顿操作下来发现并没有用,因为做了新增修改操作,缓存是失效,都会执行sql的。加了不启用一级缓存问题依旧存在。
四、灵魂质问
但为什么会有这样的问题呢?明明新增了但是查询到的条数还是0
我终于怀疑到了是mysql这里的问题了。因为mysql的事务默认是可重复读(REPEATABLE_READ)。防止脏读,非重复读。我只是在这段代码加了同步。假如第一个事务执行完这段同步代码,新增了数据。第二个事务进来后,第一个事务还没提交,第二个事务读不到数据,就会出现该问题。该死,问题找到了。
五、解决问题
解决方法,查询的时候加上数据库行锁。select * from xxx where id = xxx for update 。