@Resource
private StringRedisTemplate stringRedisTemplate;
@Override
public Result queryById(Long id) {
//1. 从redis红查询商铺缓存
String key = RedisConstants.CACHE_SHOP_KEY + id;
String shopJson = stringRedisTemplate.opsForValue().get(key);
//2. 判断是否存在
if(StringUtils.isNotBlank(shopJson)){
//存在,直接返回
Shop shop = JSONUtil.toBean(shopJson, Shop.class);
return Result.ok(shop);
}
//3. 判断命中是否是空值
if(shopJson !=null){
//返回错误信息
return Result.fail("店铺信息不存在");
}
//4. 不存在,根据id查询数据库
Shop shop = this.getById(id);
//5. 数据库不存在,返回错误
if(shop == null){
//5.1 将空值写入redis
stringRedisTemplate.opsForValue().set(key,"",RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
//5.2 返回错误信息
return Result.fail("店铺不存在");
}
//6. 存在,写入redis
stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop),RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
//7. 返回
return Result.ok(shop);
}
@Resource
private StringRedisTemplate stringRedisTemplate;
@Override
public Result queryList() {
//1. 从Redis中查
String key = RedisConstants.CACHE_SHOP_TYPE_LIST;
Boolean hasKey = stringRedisTemplate.hasKey(key);
//2. redis中存在即返回
if(hasKey){
List<String> range = stringRedisTemplate.opsForList().range(key, 0, -1);
List<ShopType> shopTypeList = range.stream()
.map(item -> JSONUtil.toBean(item,ShopType.class))
.sorted(Comparator.comparingInt(ShopType::getSort))
.collect(Collectors.toList());
return Result.ok(shopTypeList);
}
//3. redis中不存在,即查数据库
List<ShopType> typeList = this.lambdaQuery().orderByAsc(ShopType::getSort).list();
//4. 写入redis中一份
//4.1 假如mysql中也为空,则存一份空,创建key,防止缓存穿透
if(CollectionUtils.isEmpty(typeList)){
stringRedisTemplate.opsForValue()
.set(key, Collections.emptyList().toString(),RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
return Result.fail("商铺分类信息为空");
}
//4.2 数据存在,写入缓存
List<String> cache = typeList.stream()
.sorted(Comparator.comparingInt(ShopType::getSort))
.map(JSONUtil::toJsonStr)
.collect(Collectors.toList());
stringRedisTemplate.opsForList().rightPushAll(key,cache);
stringRedisTemplate.expire(key,RedisConstants.CACHE_SHOP_TYPE_TTL,TimeUnit.MINUTES);
//返回数据
return Result.ok(typeList);
}
@Override
@Transactional
public Result updateShop(Shop shop) {
Long id = shop.getId();
if(id == null) {
return Result.fail("店铺id不能为空");
}
//1. 更新数据库
this.updateById(shop);
//2. 删除缓存
stringRedisTemplate.delete(RedisConstants.CACHE_SHOP_KEY+id);
return Result.ok();
}
上文代码已处理该问题。
缓存穿透是指客户端请求的数据在缓存中和数据库中都不存在,这样缓存就永远不会生效,这些请求都会打到数据库,给数据库带来巨大压力
缓存雪崩是指在同一时段大量的缓存key同时失效或者Redis服务宕机,导致大量请求达到数据库,带来巨大压力。
缓存击穿问题也称热点key问题,就是一个被高并发访问并且缓存重建业务较复杂的key突然失效了,无数的请求瞬间给数据库带来巨大的冲击。
@Override
public Result queryById(Long id) {
Shop shop = queryWithMutex(id);
if(shop==null){
return Result.fail("店铺不存在");
}
//7. 返回
return Result.ok(shop);
}
public Shop queryWithMutex(Long id){
//1. 从redis中查询商铺缓存
String key = RedisConstants.CACHE_SHOP_KEY + id;
String shopJson = stringRedisTemplate.opsForValue().get(key);
//2. 判断是否存在
if(StringUtils.isNotBlank(shopJson)){
//存在,直接返回
return JSONUtil.toBean(shopJson, Shop.class);
}
//3. 判断命中是否是空值
if(shopJson !=null){
//返回错误信息
return null;
}
//4. 开始实现缓存重建
//4.1 获取互斥锁
String lockKey = "lock:shop:"+id;
Shop shop = null;
try{
Boolean isLock = tryLock(lockKey);
//4.2 判断是否获取成功
while (!isLock) {
//4.3 失败,休眠并重试
Thread.sleep(50);
}
//doubleCheck
key = RedisConstants.CACHE_SHOP_KEY + id;
shopJson = stringRedisTemplate.opsForValue().get(key);
if (StringUtils.isNotBlank(shopJson)) {
return JSONUtil.toBean(shopJson, Shop.class);
}
if (shopJson != null) {
return null;
}
//4.3 成功,根据id查询数据库
shop = this.getById(id);
//5. 数据库不存在,返回错误
if (shop == null) {
//5.1 将空值写入redis
stringRedisTemplate.opsForValue().set(key, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
//5.2 返回错误信息
return null;
}
//6. 存在,写入redis
stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
}catch (InterruptedException e){
throw new RuntimeException(e);
}finally {
//7.释放互斥锁
unLock(lockKey);
}
//8. 返回
return shop;
}
//获取锁
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);
}
@Data
public class RedisData {
private LocalDateTime expireTime;
private Object data;
}
@Resource
private StringRedisTemplate stringRedisTemplate;
@Override
public Result queryById(Long id) {
Shop shop = queryWithExpire(id);
//7. 返回
return Result.ok(shop);
}
private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);
//逻辑过期方法
public Shop queryWithExpire(Long id){
//1. 从redis中查询商铺缓存
String key = RedisConstants.CACHE_SHOP_KEY + id;
String shopJson = stringRedisTemplate.opsForValue().get(key);
//2. 判断是否存在
if(StringUtils.isBlank(shopJson)){
//3. 不存在,直接返回
return null;
}
//4. 命中,需要先把json反序列化为对象
RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
Shop shop = JSONUtil.toBean((JSONObject)redisData.getData(), Shop.class);
LocalDateTime expireTime = redisData.getExpireTime();
//5. 判断是否过期
if(expireTime.isAfter(LocalDateTime.now())){
//5.1 未过期,直接返回
return shop;
}
//5.2 已过期,需要重新缓存重建
//6. 缓存重建
//6.1 获取互斥锁
String lockKey = RedisConstants.LOCK_SHOP_KEY+id;
Boolean isLock = tryLock(lockKey);
//6.2 判断是否获取锁成功
if (isLock){
//doubleCheck
redisData = JSONUtil.toBean(shopJson, RedisData.class);
expireTime = redisData.getExpireTime();
if(expireTime.isAfter(LocalDateTime.now())){
return shop;
}
//6.3 成功,开启独立线程,实现缓存重建
CACHE_REBUILD_EXECUTOR.submit(()->{
try {//重建缓存
this.saveShop2Redis(id,30*60L);
}catch (Exception e){
throw new RuntimeException(e);
}finally {//释放锁
unLock(lockKey);
}
});
}
//6.4 返回过期的商铺信息
return shop;
}
//存储逻辑过期函数
public void saveShop2Redis(Long id,Long expireSeconds){
//1. 查询店铺数据
Shop shop = getById(id);
//2. 封装逻辑过期时间
RedisData redisData = new RedisData();
redisData.setData(shop);
redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
//3. 写入redis
stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY+id,JSONUtil.toJsonStr(redisData));
}
基本就是上文代码改泛型。
@Component
@Slf4j
public class CacheClient {
private StringRedisTemplate stringRedisTemplate;
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)));
stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData),time,unit);
}
public <R,ID> R queryWithPassThrough(String keyPrefix, ID id, Class<R> type, Function<ID,R> dbFallback, Long time, TimeUnit unit){
String key = keyPrefix + id;
String json = stringRedisTemplate.opsForValue().get(key);
if(StringUtils.isNotBlank(json)){
return JSONUtil.toBean(json, type);
}
if(json != null){
return null;
}
R r = dbFallback.apply(id);
if(r == null){
stringRedisTemplate.opsForValue().set(key,"",RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
//5.2 返回错误信息
return null;
}
//6. 存在,写入redis
this.set(key,r,time,unit);
return r;
}
private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);
public <R, ID> R queryWithLogicExpire(String keyPrefix, ID id, Class<R> type, Function<ID,R> dbFallback, Long time, TimeUnit unit){
String key = RedisConstants.CACHE_SHOP_KEY + id;
String shopJson = stringRedisTemplate.opsForValue().get(key);
if(StringUtils.isBlank(shopJson)){
return null;
}
RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
R r = JSONUtil.toBean((JSONObject)redisData.getData(), type);
LocalDateTime expireTime = redisData.getExpireTime();
if(expireTime.isAfter(LocalDateTime.now())){
return r;
}
String lockKey = RedisConstants.LOCK_SHOP_KEY+id;
Boolean isLock = tryLock(lockKey);
if (isLock){
redisData = JSONUtil.toBean(shopJson, RedisData.class);
expireTime = redisData.getExpireTime();
if(expireTime.isAfter(LocalDateTime.now())){
return r;
}
CACHE_REBUILD_EXECUTOR.submit(()->{
try {//重建缓存
R r1 = dbFallback.apply(id);
this.setWithLogicalExpire(key,r1,time,unit);
}catch (Exception e){
throw new RuntimeException(e);
}finally {//释放锁
unLock(lockKey);
}
});
}
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);
}
}