自定义Redis工具类(解决缓存穿透和击穿)

自己封装了一个Redis工具类,帮助完成开发中的缓存穿透,缓存击穿的问题。

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

/**
 * @description: Redis缓存工具类
 * @author: gunala
 * @date: 2024/3/23 20:02
 */
@Component
public class RedisCache {
    
    private final StringRedisTemplate redisTemplate;
    
    public RedisCache(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public static final Long CACHE_NULL_TTL = 1L;

    public static final String CACHE_LOCK_KEY = "lock:";

    //自定义线程池
    private final ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
            5,
            10,
            500L,
            TimeUnit.MILLISECONDS,
            new LinkedBlockingDeque<>(5),
            new ThreadPoolExecutor.CallerRunsPolicy());

    /**
     * 设置缓存数据,并指定过期时间
     * @param key 缓存键
     * @param value 缓存值
     * @param time 过期时间(单位:秒)
     */
    public void set(String key,Object value,long time){
        redisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value),time, TimeUnit.SECONDS);
    }

    /**
     * 设置缓存数据,并指定过期时间
     * @param key 缓存键
     * @param value 缓存值
     * @param time 过期时间
     * @param unit 时间单位
     */
    public void set(String key,Object value,long time,TimeUnit unit){
        redisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value),time,unit);
    }


    /**
     * 从 Redis 缓存中根据指定的键获取存储的对象
     * @param key 缓存键
     * @param type 对象的类型
     * @return 获取到的对象,如果不存在则返回null
     */
    public <T> T get(String key,Class<T> type){
        String objectJson = redisTemplate.opsForValue().get(key);
        if (StrUtil.isBlank(objectJson)){
            return null;
        }
        return JSONUtil.toBean(objectJson,type);
    }


    /**
     * 删除指定key对应的缓存数据
     * @param key 待删除的缓存数据的key
     */

    public void delete(String key){
        redisTemplate.delete(key);
    }


    /**
     * 缓存穿透处理方法,用于从缓存中获取数据,如果缓存中不存在,则调用指定函数生成数据并存入缓存
     * @param prefix 缓存键前缀
     * @param id 缓存数据的唯一标识
     * @param time 缓存过期时间(单位:分钟)
     * @param type 返回结果的类型
     * @param function 生成数据的函数
     * @return 获取到的数据,如果缓存中不存在且生成函数返回null,则返回null
     */
    public <T,R> T cachePenetration (String prefix, R id, Long time, Class<T> type, Function<R,T> function){
        // 拼接缓存键名
        String key = prefix + id;
        // 从 Redis 中获取缓存数据
        String objectJson = redisTemplate.opsForValue().get(key);
        // 如果缓存数据不为空,则将 JSON 转换为指定类型对象并返回
        if (StrUtil.isNotBlank(objectJson)){
            return JSONUtil.toBean(objectJson, type);
        }
        // 如果缓存数据为空字符串,则返回 null
        if ("".equals(objectJson)){
            return null;
        }
        // 调用传入的函数生成结果
        T result = function.apply(id);
        // 将结果转换为 JSON 格式并存入 Redis 缓存中,设置过期时间
        redisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(result), time, TimeUnit.MINUTES);
        return result;
    }

    /**
     * 缓存击穿处理方法
     * @param prefix 缓存前缀
     * @param id 缓存标识
     * @param time 缓存过期时间
     * @param type 返回对象类型
     * @param function 处理函数
     * @return T 返回结果对象
     */
    public <T,R> T cacheBreakdown (String prefix,R id, Long time, Class<T> type, Function<R,T> function){
        String key = prefix + id; // 拼接缓存key
        String objectJson = redisTemplate.opsForValue().get(key); // 获取缓存中的数据

        // 判断缓存中是否有数据
        if (StrUtil.isNotBlank(objectJson)){
            return JSONUtil.toBean(objectJson,type); // 将缓存数据转换为指定类型并返回
        }

        // 缓存中无数据时的处理
        if ("".equals(objectJson)){
            return null; // 返回空值
        }

        T result = null; // 初始化返回结果对象

        try{
            Boolean lock = lock(CACHE_LOCK_KEY, CACHE_NULL_TTL); // 获取缓存锁
            if (lock){
                if (redisTemplate.opsForValue().get(key) != null){
                    return JSONUtil.toBean(redisTemplate.opsForValue().get(key),type); // 返回缓存中的数据
                }
                result = function.apply(id); // 调用处理函数处理数据
                if (result == null){
                    redisTemplate.opsForValue().set(key,"",time,TimeUnit.MINUTES); // 将空值缓存起来
                    return null; // 返回空值
                }
                redisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(result),time,TimeUnit.MINUTES); // 将处理结果缓存起来
            }else {
                try {
                    Thread.sleep(100); // 等待一段时间
                    result = cacheBreakdown(prefix,id,time,type,function); // 递归调用缓存击穿处理方法
                } catch (InterruptedException e) {
                    throw new RuntimeException(e); // 抛出异常
                }
            }
        }finally {
            unlock(CACHE_LOCK_KEY); // 释放缓存锁
        }

        return result; // 返回处理结果对象
    }

    /**
     * 根据逻辑时间进行缓存处理
     * @param prefix 缓存键前缀
     * @param id 缓存对象的唯一标识
     * @param time 缓存时间
     * @param type 返回结果的类型
     * @param function 处理缓存数据的函数
     * @return 返回处理后的缓存数据,如果缓存未命中或已过期则返回null
     */
    public <T,R> T cacheBreakdownByLogicalTime (String prefix,R id,Long time, Class<T> type, Function<R,T> function){
        // 拼接缓存键
        String key = prefix + id;
        // 从Redis中获取缓存数据
        String objectJson = redisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(objectJson)){
            // 如果缓存数据不为空
            RedisData data = JSONUtil.toBean(objectJson, RedisData.class);
            if (data.getExpireTime().isAfter(LocalDateTime.now())){
                // 如果缓存未过期,则直接返回缓存数据
                return JSONUtil.toBean((JSONObject) data.getData(),type);
            }
            else {
                // 如果缓存已过期,则尝试获取缓存写锁
                boolean lock = lock(CACHE_LOCK_KEY, CACHE_NULL_TTL);
                if (lock){
                    // 如果成功获取到锁,则在线程池中异步处理缓存数据
                    threadPool.submit(()->{
                        try {
                            // 调用处理缓存数据的函数
                            T result = function.apply(id);
                            if (result == null){
                                // 如果处理结果为空,则将空字符串写入缓存
                                redisTemplate.opsForValue().set(key,"",time,TimeUnit.MINUTES);
                            }else {
                                // 如果处理结果不为空,则更新缓存数据
                                RedisData redisData = new RedisData();
                                redisData.setData(result);
                                redisData.setExpireTime(LocalDateTime.now().plusSeconds(time));
                                redisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(redisData),time,TimeUnit.MINUTES);
                            }
                        } catch (Exception e) {
                            // 捕获异常并抛出运行时异常
                            throw new RuntimeException(e);
                        }finally {
                            // 释放缓存写锁
                            unlock(CACHE_LOCK_KEY);
                        }

                    });
                }
            }
        }
        // 返回null表示缓存未命中或已过期
        return null;
    }

    /**
     * 尝试在 Redis 中对指定 key 加锁
     * @param key 锁的键名
     * @param time 锁的超时时间(单位:分钟)
     * @return 加锁是否成功
     */
    public boolean lock(String key, long time){
        // 调用 RedisTemplate 的 opsForValue 方法获取 Value 操作对象,然后调用 setIfAbsent 方法尝试在 Redis 中设置指定 key 的值为 "1",并设置超时时间
        Boolean flag = redisTemplate.opsForValue().setIfAbsent(key, "1", time, TimeUnit.MINUTES);
        // 返回加锁是否成功的布尔值,使用 BooleanUtil.isTrue 方法将 Boolean 对象转换为 boolean 类型
        return BooleanUtil.isTrue(flag);
    }

    /**
     * 从 Redis 缓存中删除指定的 key 对应的数据
     * @param key 要删除的数据的 key
     */
    public void unlock(String key){
        redisTemplate.delete(key);
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Gunalaer

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值