在大并发读的情景下有很大概率遇到缓存失效问题,缓存失效问题主要有以下三种:缓存雪崩,缓存击穿和缓存穿透。
缓存雪崩
缓存雪崩是指同一时间段大量的缓存key同时失效或者Redis服务宕机,导致大量请求打到数据库,带来巨大压力
缓存雪崩是指我们设置缓存的时候采用了相同的过期时间,导致缓存在某一时刻同时失效,恰巧那一时刻并发量很大,导致所有请求转发到数据库,数据库瞬时压力过重崩溃,从而导致系统崩溃。
解决:通常我们会给缓存在原来失效时间的基础上增加一个随机值,例如1-5分钟随机,这样会大大降低缓存过期时间的重复概率,从而避免缓存集体失效。
- 给不同的key的TTL添加随机值;
- 利用Redis集群提高服务的可用性;
- 给缓存添加降级限流策略;
- 给业务添加多级缓存;
缓存击穿
缓存击穿也叫热点key问题,就是一个被高并发访问并且缓存重建业务较复杂的key失效了,无数的请求访问会在瞬间打到数据库,带来巨大压力
某些被设置了过期时间的 key 可能被同一时间被超高并发访问,比如双十一定点抢购某一商品的信息,这种数据被称为热点数据。如果这个 key 在大量请求同时进来的时候正好过期失效,那么对于这个 key 的相关查询全部落到数据库,导致数据库崩溃,这种现象称之为缓存击穿。
解决:使用分布式锁,在缓存同时失效的情况下,保证只放行一个请求读取数据库并更新缓存。
- 通过互斥锁解决缓存击穿
给缓存重建过程加锁,确保重建过程只有一个线程执行,其它线程等待。
互斥锁的最大问题是,线程等待问题,性能较差。
- 根据id查询商品信息,基于互斥锁解决缓存击穿问题
-
通过逻辑过期解决缓存击穿
逻辑过期的优点是性能好,缺点是不保证一致性,有额外的内存消耗,实现复杂。
缓存穿透
缓存穿透是指客户端请求的数据在Redis和数据库中都不存在,这样就无法进行缓存,这些请求(查询不存在的数据)都会打到数据库。
缓存穿透是指查询一个一定不存在的数据,由于缓存不命中,程序会去查询数据库,但是数据库也无此记录,这将导致这个不存在的数据每次请求都要到数据库去查询,缓存形同虚设,当流量大时,数据库可能因此挂掉
解决:
- 缓存空结果 且 设置短的过期时间(简单粗暴)
对不存在的数据也在Redis中建立缓存,值为空,并设置一个较短的TTL时间。
优点:实现简单,维护方便;
缺点:额外的内存消耗,可能造成短期的数据不一致;
- 布隆过滤器
利用布隆过滤算法,在请求进入Redis之前,先判断是否存在,如果不存在则直接拒绝访问。
优点:内存占用小
缺点:① 实现复杂;② 存在误判的可能;
Redis工具类
// 解决缓存穿透
Goods goods = cacheClient.queryWithPassThrough(CACHE_GOODS_KEY, id, Goods.class, this::getById, CACHE_GOODS_TTL, TimeUnit.MINUTES);
// 互斥锁解决缓存击穿
Goods goods = cacheClient.queryWithMutex(CACHE_GOODS_KEY, id, Goods.class, this::getById, CACHE_GOODS_TTL, TimeUnit.MINUTES);
// 逻辑过期解决缓存击穿
Goods goods = cacheClient.queryWithLogicalExpire(CACHE_GOODS_KEY, id, Goods.class, this::getById, 20L, TimeUnit.SECONDS);
package com.guor.utils;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
@Slf4j
@Component
public class CacheClient {
private final StringRedisTemplate stringRedisTemplate;
private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);
public CacheClient(StringRedisTemplate stringRedisTemplate) {
this.stringRedisTemplate = stringRedisTemplate;
}
public void set(String key, Object value, Long time, TimeUnit unit) {
stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), time, unit);
}
public void setWithLogicalExpire(String key, Object value, Long time, TimeUnit unit) {
// 设置逻辑过期
RedisData redisData = new RedisData();
redisData.setData(value);
redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
// 写入Redis
stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
}
public <R,ID> R queryWithPassThrough(String keyPrefix, ID id, Class<R> type, Function<ID, R> dbFallback, Long time, TimeUnit unit){
String key = keyPrefix + id;
// 1.从redis查询商铺缓存
String json = stringRedisTemplate.opsForValue().get(key);
// 2.判断是否存在
if (StrUtil.isNotBlank(json)) {
// 3.存在,直接返回
return JSONUtil.toBean(json, type);
}
// 判断命中的是否是空值
if (json != null) {
// 返回一个错误信息
return null;
}
// 4.不存在,根据id查询数据库
R r = dbFallback.apply(id);
// 5.不存在,返回错误
if (r == null) {
// 将空值写入redis
stringRedisTemplate.opsForValue().set(key, "", RedisConfig.CACHE_NULL_TTL, TimeUnit.MINUTES);
// 返回错误信息
return null;
}
// 6.存在,写入redis
this.set(key, r, time, unit);
return r;
}
public <R, ID> R queryWithLogicalExpire(String keyPrefix, ID id, Class<R> type, Function<ID, R> dbFallback, Long time, TimeUnit unit) {
String key = keyPrefix + id;
// 1.从redis查询商铺缓存
String json = stringRedisTemplate.opsForValue().get(key);
// 2.判断是否存在
if (StrUtil.isBlank(json)) {
// 3.存在,直接返回
return null;
}
// 4.命中,需要先把json反序列化为对象
RedisData redisData = JSONUtil.toBean(json, RedisData.class);
R r = JSONUtil.toBean((JSONObject) redisData.getData(), type);
LocalDateTime expireTime = redisData.getExpireTime();
// 5.判断是否过期
if(expireTime.isAfter(LocalDateTime.now())) {
// 5.1.未过期,直接返回店铺信息
return r;
}
// 5.2.已过期,需要缓存重建
// 6.缓存重建
// 6.1.获取互斥锁
String lockKey = RedisConfig.LOCK_GOODS_KEY + id;
boolean isLock = tryLock(lockKey);
// 6.2.判断是否获取锁成功
if (isLock){
// 6.3.成功,开启独立线程,实现缓存重建
CACHE_REBUILD_EXECUTOR.submit(() -> {
try {
// 查询数据库
R newR = dbFallback.apply(id);
// 重建缓存
this.setWithLogicalExpire(key, newR, time, unit);
} catch (Exception e) {
throw new RuntimeException(e);
}finally {
// 释放锁
unlock(lockKey);
}
});
}
// 6.4.返回过期的商铺信息
return r;
}
public <R, ID> R queryWithMutex(String keyPrefix, ID id, Class<R> type, Function<ID, R> dbFallback, Long time, TimeUnit unit) {
String key = keyPrefix + id;
// 1.从redis查询商铺缓存
String json = stringRedisTemplate.opsForValue().get(key);
// 2.判断是否存在
if (StrUtil.isNotBlank(json)) {
// 3.存在,直接返回
return JSONUtil.toBean(json, type);
}
// 判断命中的是否是空值
if (json != null) {
// 返回一个错误信息
return null;
}
// 4.实现缓存重建
// 4.1.获取互斥锁
String lockKey = RedisConfig.LOCK_GOODS_KEY + id;
R r = null;
try {
boolean isLock = tryLock(lockKey);
// 4.2.判断是否获取成功
if (!isLock) {
// 4.3.获取锁失败,休眠并重试
Thread.sleep(50);
return queryWithMutex(keyPrefix, id, type, dbFallback, time, unit);
}
// 4.4.获取锁成功,根据id查询数据库
r = dbFallback.apply(id);
// 5.不存在,返回错误
if (r == null) {
// 将空值写入redis
stringRedisTemplate.opsForValue().set(key, "", RedisConfig.CACHE_NULL_TTL, TimeUnit.MINUTES);
// 返回错误信息
return null;
}
// 6.存在,写入redis
this.set(key, r, time, unit);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}finally {
// 7.释放锁
unlock(lockKey);
}
// 8.返回
return r;
}
private boolean tryLock(String key) {
Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
return BooleanUtil.isTrue(flag);
}
private void unlock(String key) {
stringRedisTemplate.delete(key);
}
}