首页 > 其他分享 >封装工具类解决缓存问题

封装工具类解决缓存问题

时间:2022-12-11 10:55:19浏览次数:36  
标签:缓存 封装 String key import return 工具 id

满足以下需求
基于StringRedisTemplate封装一个缓存工具类,满足下列需求:

  • 方法1:将任意Java对象序列化为json并存储在string类型的key中,并且可以设置TTL过期时间

  • 方法2:将任意Java对象序列化为json并存储在string类型的key中,并且可以设置逻辑过期时间,用于处理缓存击穿问题

  • 方法3:根据指定的key查询缓存,并反序列化为指定类型,利用缓存空值的方式解决缓存穿透问题

  • 方法4:根据指定的key查询缓存,并反序列化为指定类型,需要利用逻辑过期解决缓存击穿问题将逻辑进行封装


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;
import static com.hmdp.utils.RedisConstants.*;
@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, "", 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 = LOCK_SHOP_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 shopJson = stringRedisTemplate.opsForValue().get(key);
        // 2.判断是否存在
        if (StrUtil.isNotBlank(shopJson)) {
            // 3.存在,直接返回
            return JSONUtil.toBean(shopJson, type);
        }
        // 判断命中的是否是空值
        if (shopJson != null) {
            // 返回一个错误信息
            return null;
        }

        // 4.实现缓存重建
        // 4.1.获取互斥锁
        String lockKey = LOCK_SHOP_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, "", 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);
    }
}

使用时

       Shop shop=
               cacheClient.queryWithPassThrough(CACHE_SHOP_KEY,id,Shop.class,this::getById,CACHE_SHOP_TTL,TimeUnit.MINUTES);

转自黑马点评

标签:缓存,封装,String,key,import,return,工具,id
From: https://www.cnblogs.com/lhsss9825/p/16972933.html

相关文章

  • 图文成片,文本批量生成短视频工具
    1、视频生成2、输入断句后的文案3、将文案根据短句分割,每句作为一条字幕4、根据字幕搜索表情包并选择设置5、利用语音合成手段合成配音6、重复3、4步骤,直到所有的字幕......
  • 2023最新图文成片工具:文字生成视频,只需一步
    发现了「输入文字自动生成视频」的功能之后,笔者更是感到了官方的「保姆」心理。手动输入文字之后,软件可以自动根据文字推荐素材、生成录音、配好字幕BGM,并且获得一个不错......
  • 操作系统如何更新dns缓存?
    1、window环境:hosts文件位置:C:\windows\system32\drivers\etc刷新方式:win+r,输入CMD,回车在命令行执行:ipconfig/flushdns#清除DNS缓存内容。ps:ipconfig/displa......
  • 火了!快速批量生成短视频工具,导入文字自动转视频!
    从纯文字自媒体人到一键视频自媒体人,一键将文本图片转变为视频,是不是很方便?短视频的火爆,让许多人都纷纷去制作短视频,虽然有很多播放短视频的软件,但也有很多人始终没能找到......
  • 这款国产API工具也太强了吧!让我放弃了postman
    为什么弃用postman转用Eolink?程序员在接口开发完成后都通常需要自测,当返回结果根据符合预期时,则表示代表接口可用。自己以前用的是postman来进行接口测试,但postman只能进行......
  • Intelligent standby list cleaner(清理备用内存工具)--九五小庞
    Intelligentstandbylistcleaner是一款待机列表清理软件,这款工具可以帮助用户监视计算机的内存使用情况,等计算机的内存使用到一定大小后,软件会自动清理内存列表,通过这种......
  • 如何查看服务器的Raid缓存等配置的情况
    摘要最近总遇到同一批机器的IO不一样的情况.感觉可能跟硬件设备和Raid卡的设置不一样有关系.所以今天学习研究了下storcli的命令.希望能够进行一些数据的收集.Storc......
  • 封装Response对象
    封装Response对象#utils.py#自定制响应fromrest_framework.responseimportResponseclassCommonResponse(Response):def__init__(self,code=10,msg='成功'......
  • 抖音直播监控下载工具;直播下载器、24小时监控主播开播状态,开播自动下载
    软件介绍:(​​抖音直播监控​​)1.输入一次直播分享地址,以后自动监控。主播开播自动下载2.可以设置下载后自动转mp4格式3.下载后每个主播单独文件夹存放,文件名字以主播名字和......
  • JVM监控工具之jvisualvm
    一、简介JVisualVM是Netbeans的profile子项目,已在JDK6.0update7中自带(bin/jvisualvm.exe),能够监控线程,内存情况,查看方法的CPU时间和内存中的对象,已被GC的对象,反向查看......