Redis缓存穿透/击穿工具类的封装

2022-07-28,,,,

1. 简单的步骤说明

创建一个逻辑缓存数据类型

封装缓冲穿透和缓冲击穿工具

2. 逻辑缓存数据类型

这里主要是创建一个可以往redis里边存放的数据类型

redisdata 的java类型

import lombok.data;

import java.time.localdatetime;

@data
public class redisdata {
    private localdatetime expiretime;
    private object data;
}

3. 缓冲工具类的封装

3.1 cacheclient 类的类图结构

3.2 cacheclient 类代码

import cn.hutool.core.util.booleanutil;
import cn.hutool.core.util.strutil;
import cn.hutool.json.jsonobject;
import cn.hutool.json.jsonutil;
import com.hmdp.entity.shop;
import lombok.data;
import lombok.extern.slf4j.slf4j;
import org.springframework.data.redis.core.stringredistemplate;
import org.springframework.stereotype.component;

import javax.annotation.resource;
import java.time.localdatetime;
import java.util.concurrent.executorservice;
import java.util.concurrent.executors;
import java.util.concurrent.timeunit;
import java.util.function.function;

import static com.hmdp.utils.redisconstants.*;

@component
@slf4j
public class cacheclient {

    @resource
    private final stringredistemplate stringredistemplate;

    // 线程池对象
    private static final executorservice cache_rebuild_executor = executors.newfixedthreadpool(10);

    /**
     * 注入stringredistemplate的构造方法
     * @param stringredistemplate
     */
    public cacheclient(stringredistemplate stringredistemplate) {
        this.stringredistemplate = stringredistemplate;
    }

    /**
     * 在redis中实现物理上添加数据和设置有效期
     * @param key : redis 存储的key的值
     * @param value : redis 存储的value的值
     * @param time : redis 存储的逻辑过期时间的值
     * @param unit :redis 存储的逻辑过期时间的单位
     */
    public void set(string key, object value, long time, timeunit unit) {
        stringredistemplate.opsforvalue().set(key, jsonutil.tojsonstr(value), time, unit);
    }

    /**
     * 解决缓存击穿的rides的逻辑存储的方法
     * @param key : redis 存储的key的值
     * @param value : redis 存储的value的值
     * @param time : redis 存储的逻辑过期时间的值
     * @param unit :redis 存储的逻辑过期时间的单位
     */
    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));
    }

    /**
     *  解决缓存穿透问题的reids查询方法
     * @param keyprefix : key的前缀
     * @param id : 查询的id
     * @param type : 查询数据的class类型
     * @param dbfallback : 查询数据库的sql具体语句
     * @param time : 设置超时间
     * @param unit : 设置超时时间单位
     * @return : 返回一个 设置的 class 类型对象
     * @param <r> 返回值类型参数泛型
     * @param <t> id类型参数泛型
     */
    public <r, t> r querywithpassthrough(
            string keyprefix, t id, class<r> type, function<t, 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) {
            stringredistemplate.opsforvalue().set(key, "", cache_null_ttl, timeunit.minutes);
            return null;
        }
        // 6. 写入redis
        this.set(key, r, time, unit);
        // 7. 返回
        return r;
    }

    /**
     *  解决缓存击穿问题的reids查询方法
     * @param keyprefix : key的前缀
     * @param id : 查询的id
     * @param type : 查询数据的class类型
     * @param dbfallback : 查询数据库的sql具体语句
     * @param time : 设置超时间
     * @param unit : 设置超时时间单位
     * @return : 返回一个 设置的 class 类型对象
     * @param <r> 返回值类型参数泛型
     * @param <t> id类型参数泛型
     */
    public <r, t> r querywithlogicalexpire(
            string keyprefix, t id, class<r> type, function<t, r> dbfallback, long time, timeunit unit) {

        string key = keyprefix + id;
        // 1. 从 redis 查询缓存
        string json = stringredistemplate.opsforvalue().get(key);
        // 2. 判断是否存在
        if (strutil.isblank(json)) {
            return null;
        }

        // 4. 命中需要判断过期时间
        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 = lock_shop_key + id;
        // 6.2 判断是否获取锁成功
        boolean islock = trylock(lockkey);
        if (islock) {
            // 6.3 成功 开启独立线程,实现缓存重建
            cache_rebuild_executor.submit(() -> {
                try {
                    // 查询数据库
                    r r1 = dbfallback.apply(id);
                    // 写入redis
                    this.setwithlogicalexpire(key, r1, time, unit);
                } catch (exception e) {
                    throw new runtimeexception(e);
                } finally {
                    // 释放锁
                    unlock(lockkey);
                }
            });
        }
        // 6.4 返回店铺信息
        return r;
    }

    /**
     *
     * @param key
     * @return
     */
    private boolean trylock(string key) {
        boolean flag = stringredistemplate.opsforvalue().setifabsent(key, "1", 10, timeunit.seconds);
        return booleanutil.istrue(flag);
    }

    /**
     * 释放错
     *
     * @param key
     */
    private void unlock(string key) {
        stringredistemplate.delete(key);
    }


}

到此这篇关于redis缓存穿透/击穿工具类的封装的文章就介绍到这了,更多相关redis缓存穿透 击穿内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

《Redis缓存穿透/击穿工具类的封装.doc》

下载本文的Word格式文档,以方便收藏与打印。