插入或者更新的并发情况处理
发布日期:2021-06-30 16:14:14 浏览次数:2 分类:技术文章

本文共 1933 字,大约阅读时间需要 6 分钟。

最近接收的代码经常出现并发问题。操作分为两步,第一步查询是否存在,如果不存在插入,存在更新。

关键是查询判断和后面的插入或者更新不是原子操作,如果判断之后,其他线程进行了插入操作,抛出唯一key异常。

private void insertOrUpdateCaseExpand(RobotCaseUpdateDTO updateDTO, RobotAddPaymentDTO addPaymentDTO) {        // 查询还款扩展表        RobotCaseExpand expandOld = getRobotCaseExpand(updateDTO.getId());        logger.info("添加或更新案件扩展表信息:"+JSON.toJSONString(expandOld));        if (Objects.nonNull(expandOld)) {            expandOld.setLastRepayRecord(addPaymentDTO.getPaymentId());            BigDecimal paidAmount = expandOld.getPaidAmount().add(addPaymentDTO.getRepayAmount());            expandOld.setPaidAmount(paidAmount);            expandOld.setUpdateTime(new Date());            robotCaseExpandMapper.updateByPrimaryKeySelective(expandOld);        } else {            RobotCaseExpand robotCaseExpandNew = new RobotCaseExpand();            robotCaseExpandNew.setId(IDUtil.nextId());            robotCaseExpandNew.setCaseId(updateDTO.getId());            robotCaseExpandNew.setCompanyId(addPaymentDTO.getCompanyId());            robotCaseExpandNew.setLastRepayRecord(addPaymentDTO.getPaymentId());            robotCaseExpandNew.setPaidAmount(addPaymentDTO.getRepayAmount());            robotCaseExpandNew.setCreateTime(new Date());            robotCaseExpandNew.setUpdateTime(new Date());            robotCaseExpandMapper.insertSelective(robotCaseExpandNew);        }    }

思考一下,根据业务场景,考虑以下方案:

1. 缓存层加分布式锁,如果是单机服务,利用JVM锁。分布式锁可以利用redis、zookeeper等

2. 数据库增加唯一索引,如果并发,抛出异常,进行补偿。精准定位问题,不影响大多数情况。第一个方法所有都需要加锁,解锁

3.利用临时表,在第二个插入逻辑等时候,利用sql进行判断,是否存在,但是这样无法插入,虽然不报错,丢失这次本应该更新等数据。

sql语句写法:

INSERT INTO `robot_case_expand` (`id`, `company_id`, `case_id`, `paid_amount`, `last_repay_record`, `create_time`, `update_time`)select 1000000734004445, 24, 100000072099654, 2104.80, 100000073400447, '2018-10-09 21:43:03', '2018-10-09 21:43:04'from  dual where not exists   (select     *   from    `robot_case_expand`   where `case_id`= '100000072099654')

 

转载地址:https://kerry.blog.csdn.net/article/details/103514513 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:mysql-innodb-undo和redo
下一篇:mysql 优化总结

发表评论

最新留言

网站不错 人气很旺了 加油
[***.192.178.218]2024年05月04日 04时25分19秒