Redis缓存穿透、击穿、雪崩到底是个啥?7张图告诉你

一、缓存是什么?

缓存就是数据交换的缓存区,是存储数据的地方,一般读写性能较高。

043497cbf501c21696c27d0d0177ad76.png

二、缓存的作用和成本

1、缓存的作用:

  1. 降低后端负载

  2. 提高读写效率,降低响应时间

2、缓存的成本:

  1. 数据一致性成本

  2. 代码维护成本

  3. 运维成本

三、缓存作用模型

b8f0cc54df9b17baa2f6dbc92ffc0005.png

1、根据id查询数据缓存流程

7c0dac4ef53aa91849a27d78a4aa56db.png

四、缓存更新策略

1、内存淘汰

Redis的内存淘汰机制,当内存不足时自动淘汰部分数据,下次查询时更新缓存。

2、超时剔除

当缓存数据设置TTL时间,到期后自动删除缓存,下次查询时更新缓存。

3、主动更新

编写业务逻辑,在修改数据库的同时,更新缓存。

五、缓存穿透

缓存穿透是指客户端请求的数据在Redis和数据库中都不存在,这样就无法进行缓存,这些请求都会打到数据库。

解决方法:

1、缓存空对象

对不存在的数据也在Redis中建立缓存,值为空,并设置一个较短的TTL时间。

优点:实现简单,维护方便;

缺点:额外的内存消耗,可能造成短期的数据不一致;

2、布隆过滤器

利用布隆过滤算法,在请求进入Redis之前,先判断是否存在,如果不存在则直接拒绝访问。

优点:内存占用小

缺点:① 实现复杂;② 存在误判的可能;

六、缓存雪崩

缓存雪崩是指同一时间段大量的缓存key同时失效或者Redis服务宕机,导致大量请求打到数据库,带来巨大压力。

解决方式:

给不同的key的TTL添加随机值;

利用Redis集群提高服务的可用性;

给缓存添加降级限流策略;

给业务添加多级缓存;

七、缓存击穿

缓存击穿也叫热点key问题,就是一个被高并发访问并且缓存重建业务较复杂的key失效了,无数的请求访问会在瞬间打到数据库,带来巨大压力。

1、通过互斥锁解决缓存击穿

给缓存重建过程加锁,确保重建过程只有一个线程执行,其它线程等待。

互斥锁的最大问题是,线程等待问题,性能较差。

a4827ed97012407d44cc81f28edfc89f.png

2、根据id查询商品信息,基于互斥锁解决缓存击穿问题

66f78cc03c9fe4c4cb4eb419806aa200.png

3、通过逻辑过期解决缓存击穿

逻辑过期的优点是性能好,缺点是不保证一致性,有额外的内存消耗,实现复杂。

4ebff5aa6c66cfc56c49b8190e73ff13.png

e65637f3e8c503ba2d8583213843015e.png

八、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);
    }
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值