缓存与数据库双写不一致

在并发场景下,同时操作数据库和缓存会存在数据不一致的情况。

本文通过模拟实现并发场景缓存与数据库双写不一致的情形,并采用分布式读锁解决此问题。

为实现并发场景,通过jmeter模拟50个线程在1秒内访问接口。

1.读取缓存,更新数据库和缓存,其余代码忽略。

@PostMapping("/updateScore")
public String updateScoreByStudentId (@RequestParam Long studentId, @RequestParam String subject) {
    String key = "student_"+studentId;
    Integer score = Integer.parseInt(stringRedisTemplate.opsForValue().get(key));
    SysScore sysScore = new SysScore();
    sysScore.setScore(score - 1);
    sysScore.setStudentId(studentId);
    sysScore.setSubject(subject);
    stringRedisTemplate.opsForValue().set(key,String.valueOf(sysScore.getScore()));
    studentService.updateScoreByStudentId(sysScore);
    return "success";
}

结果

缓存

127.0.0.1:6379> get student_3

"72"

数据库

3 数学 91

出现缓存与数据库双写不一致的场景

2.加入分布式读写锁(不能用需要读写的key来实现锁),读取缓存前加锁,更新完缓存和数据库后释放锁。

@PostMapping("/updateScore")
public String updateScoreByStudentId (@RequestParam Long studentId, @RequestParam String subject) {
    String key = "student_"+studentId;
    RReadWriteLock readWriteLock = redisson.getReadWriteLock("student_score_3");
    RLock wLock = readWriteLock.writeLock();
    wLock.lock();
    Integer score = Integer.parseInt(stringRedisTemplate.opsForValue().get(key));
    SysScore sysScore = new SysScore();
    sysScore.setScore(score - 1);
    sysScore.setStudentId(studentId);
    sysScore.setSubject(subject);
    stringRedisTemplate.opsForValue().set(key,String.valueOf(sysScore.getScore()));
    studentService.updateScoreByStudentId(sysScore);
    wLock.unlock();
    return "success";
}

结果

缓存

127.0.0.1:6379> get student_3

"50"

数据库

3 数学 50

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值