为什么db和redis缓存会不一致:
高并发的情况下——update请求,value更新的那段时间,缓存中数据被删了,没有数据,此时select这条数据的所有请求进入数据库,但是update请求还没提交,此时select读出数据并写入缓存的都是更新前的数据,都是脏数据,在update更新数据库并写入redis这段时间,此数据的select查询的都是之前的脏数据。
1.解决方法:select for update
2.原理:select sql查询的时候,如果存在update语句,此时,查询的sql会被阻塞,等待update更新完,才会执。
3.例子:
a. select的sql
b.posrtman测一下
这里没有update时,select无阻塞。
c.update业务打断点,模拟update更新时占用的时间
d.postman发起update请求
e.postman发起select请求
这里看到select请求阻塞了,因为sql是for update,在更新时,查询的sql阻塞。
f.放开debug,看结果
此时update更新完成。
此时select查询也返回,为最新内容。
redis的缓存在查询结果前删,set在返回前做就可以了,(set操作也可以用mq做异步更新)。这理牺牲了一丢丢性能,但是保证了db和redis缓存的一致性。
这里提供个 路人甲大佬 (在我关注里) 使用setnx优化的工具类。将此刻除了第一条的所有select请求睡一秒,然后这些请求会从更新后的redis里取结果!!!,减轻此update时间段的数据库压力。
public class CacheUtil {
//根据key获取缓存中对应的value
public static String getCache(String key) throws InterruptedException {
String value = RedisUtils.get(key);
if (value != null) {
return value;
}
//过期时间为当前时间+5秒
String expireTimeKey = key + "ExpireTime";
long expireTimeValue = System.currentTimeMillis() + 5000;
//setnx是原子操作,所以只有一个会成功
int setnx = RedisUtils.setnx(expireTimeKey, expireTimeValue + "");
if (setnx == 0) {
expireTimeValue = Long.valueOf(RedisUtils.get(expireTimeKey));
//如果expireTimeValue小于当前时间,说明expireTimeKey过期了,将其删除
if (System.currentTimeMillis() > expireTimeValue) {
//将expireTimeKey对应的删除
RedisUtils.del(expireTimeKey);
} else {
//休眠1秒继续获取
TimeUnit.SECONDS.sleep(1);
}
//重试
return getCache(key);
} else {
//1. 开启db事务
start transaction;
//2. 执行update t set v = #v# where t.key = #key# for update; 将v的值赋值给value
select v from t# where t.key = #key# for update;
RedisUtils.set(key, value);
//3.提交db事务
commit transaction;
}
return value;
}
//redis工具类,内部方法为伪代码
public static class RedisUtils {
//根据key获取value
public static String get(String key) {
return null;
}
//设置key对应的value
public static void set(String key, String value) {
}
//删除redis中一个key对应的值
public static void del(String key) {
}
//setnx的含义就是SET if Not Exists,该方法是原子的,如果key不存在,
//则设置当前key成功,返回1;如果当前key已经存在,则设置当前key失败,返回0
public static int setnx(String key, String value) {
return 1;
}
}
}