日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

Redis緩存穿透/擊穿工具類的封裝_Redis

作者:知識(shí)的搬運(yùn)工旺仔 ? 更新時(shí)間: 2022-09-19 編程語(yǔ)言

1. 簡(jiǎn)單的步驟說(shuō)明

創(chuàng)建一個(gè)邏輯緩存數(shù)據(jù)類型

封裝緩沖穿透和緩沖擊穿工具類

2. 邏輯緩存數(shù)據(jù)類型

這里主要是創(chuàng)建一個(gè)可以往Redis里邊存放的數(shù)據(jù)類型

RedisData 的Java類型

import lombok.Data;

import java.time.LocalDateTime;

@Data
public class RedisData {
    private LocalDateTime expireTime;
    private Object data;
}

3. 緩沖工具類的封裝

3.1 CacheClient 類的類圖結(jié)構(gòu)

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;

    // 線程池對(duì)象
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    /**
     * 注入StringRedisTemplate的構(gòu)造方法
     * @param stringRedisTemplate
     */
    public CacheClient(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * 在Redis中實(shí)現(xiàn)物理上添加數(shù)據(jù)和設(shè)置有效期
     * @param key : Redis 存儲(chǔ)的key的值
     * @param value : Redis 存儲(chǔ)的value的值
     * @param time : Redis 存儲(chǔ)的邏輯過(guò)期時(shí)間的值
     * @param unit :Redis 存儲(chǔ)的邏輯過(guò)期時(shí)間的單位
     */
    public void set(String key, Object value, Long time, TimeUnit unit) {
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), time, unit);
    }

    /**
     * 解決緩存擊穿的Rides的邏輯存儲(chǔ)的方法
     * @param key : Redis 存儲(chǔ)的key的值
     * @param value : Redis 存儲(chǔ)的value的值
     * @param time : Redis 存儲(chǔ)的邏輯過(guò)期時(shí)間的值
     * @param unit :Redis 存儲(chǔ)的邏輯過(guò)期時(shí)間的單位
     */
    public void setWithLogicalExpire(String key, Object value, Long time, TimeUnit unit) {
        // 設(shè)置邏輯過(guò)期時(shí)間
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        // 寫入Redis
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }

    /**
     *  解決緩存穿透問(wèn)題的Reids查詢方法
     * @param keyPrefix : key的前綴
     * @param id : 查詢的id
     * @param type : 查詢數(shù)據(jù)的Class類型
     * @param dbFallback : 查詢數(shù)據(jù)庫(kù)的sql具體語(yǔ)句
     * @param time : 設(shè)置超時(shí)間
     * @param unit : 設(shè)置超時(shí)時(shí)間單位
     * @return : 返回一個(gè) 設(shè)置的 Class 類型對(duì)象
     * @param <R> 返回值類型參數(shù)泛型
     * @param <T> id類型參數(shù)泛型
     */
    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) {
            // 返回錯(cuò)誤信息
            return null;
        }
        // 4. 不存在,根據(jù)id 查詢數(shù)據(jù)庫(kù)
        R r = dbFallback.apply(id);
        // 5. 不存在,返回錯(cuò)誤
        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;
    }

    /**
     *  解決緩存擊穿問(wèn)題的Reids查詢方法
     * @param keyPrefix : key的前綴
     * @param id : 查詢的id
     * @param type : 查詢數(shù)據(jù)的Class類型
     * @param dbFallback : 查詢數(shù)據(jù)庫(kù)的sql具體語(yǔ)句
     * @param time : 設(shè)置超時(shí)間
     * @param unit : 設(shè)置超時(shí)時(shí)間單位
     * @return : 返回一個(gè) 設(shè)置的 Class 類型對(duì)象
     * @param <R> 返回值類型參數(shù)泛型
     * @param <T> id類型參數(shù)泛型
     */
    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. 命中需要判斷過(guò)期時(shí)間
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        R r = JSONUtil.toBean((JSONObject) redisData.getData(), type);
        LocalDateTime expireTime = redisData.getExpireTime();
        // 5. 判斷是否過(guò)期
        if (expireTime.isAfter(LocalDateTime.now())) {
            // 5.1 未過(guò)期,直接返回店鋪信息
            return r;
        }
        // 5.2 已過(guò)期,需要緩存重建
        // 6. 緩沖重建
        // 6.1 獲取互斥鎖
        String lockKey = LOCK_SHOP_KEY + id;
        // 6.2 判斷是否獲取鎖成功
        boolean isLock = tryLock(lockKey);
        if (isLock) {
            // 6.3 成功 開啟獨(dú)立線程,實(shí)現(xiàn)緩存重建
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    // 查詢數(shù)據(jù)庫(kù)
                    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);
    }

    /**
     * 釋放錯(cuò)
     *
     * @param key
     */
    private void unlock(String key) {
        stringRedisTemplate.delete(key);
    }


}

原文鏈接:https://blog.csdn.net/weixin_46213083/article/details/126005177

欄目分類
最近更新