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

一、缓存是什么

缓存就是数据交换的缓存区是存储数据的地方一般读写性能较高。
在这里插入图片描述

二、缓存的作用和成本

1、缓存的作用

  1. 降低后端负载
  2. 提高读写效率降低响应时间

2、缓存的成本

  1. 数据一致性成本
  2. 代码维护成本
  3. 运维成本

三、缓存作用模型

在这里插入图片描述

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

在这里插入图片描述

四、缓存更新策略

1、内存淘汰

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

2、超时剔除

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

3、主动更新

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

五、缓存穿透

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

解决方法

1、缓存空对象

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

  • 优点实现简单维护方便
  • 缺点额外的内存消耗可能造成短期的数据不一致

2、布隆过滤器

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

  • 优点内存占用小
  • 缺点① 实现复杂② 存在误判的可能

六、缓存雪崩

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

解决方式

  1. 给不同的key的TTL添加随机值
  2. 利用Redis集群提高服务的可用性
  3. 给缓存添加降级限流策略
  4. 给业务添加多级缓存

七、缓存击穿

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

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

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

互斥锁的最大问题是线程等待问题性能较差。
在这里插入图片描述

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

在这里插入图片描述

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

逻辑过期的优点是性能好缺点是不保证一致性有额外的内存消耗实现复杂。
在这里插入图片描述

在这里插入图片描述

八、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);
    }
}



NoSQL数据库进阶实战

NoSQL数据库进阶实战1那些年学过的NoSQL基础

NoSQL数据库进阶实战2NoSQL数据存储模式

哪吒精品系列文章

Java学习路线总结搬砖工逆袭Java架构师

10万字208道Java经典面试题总结(附答案)

Java基础教程系列

Java高并发编程系列

数据库进阶实战系列
在这里插入图片描述

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: redis

“Redis缓存穿透、击穿、雪崩到底是个啥?7张图告诉你” 的相关文章