redis缓存工具类封装

该文章展示了如何基于StringRedisTemplate创建一个缓存工具类,用于处理缓存穿透问题,包括存储Java对象为JSON字符串、设置TTL过期时间、处理逻辑过期以及使用线程池进行缓存重建。同时,文章还提供了查询方法,确保在缓存空值或过期时能正确处理。
摘要由CSDN通过智能技术生成

基于StringRedisTemplate封装缓存工具类

@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private CacheClient cacheClient;
    @Override
    public Result queryById(Long id) {
        //工具类解决缓存穿透
        Shop shop = cacheClient.queryWithPassThrough(CACHE_SHOP_KEY,id,Shop.class,this::getById,CACHE_SHOP_TTL,TimeUnit.MINUTES);
        if (shop==null) {
            return Result.fail("店铺不存在");
        }
        return Result.ok(shop);
    }
}
@Slf4j
@Component
public class CacheClient {

    private final StringRedisTemplate stringRedisTemplate;

    public CacheClient(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    //TODO 1.将任意java对象序列化为json并储存在string类型的key中,并可设置TTL过期时间
    public void set(String key, Object value, Long time, TimeUnit unit){
         stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value),time,unit);
    }

    //TODO  2.将任意java对象序列化为json并储存在key中,并可设置逻辑过期时间,处理缓存击穿
    public void setWithLogical(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));
    }

    //TODO 3.缓存空值""解决 缓存穿透
    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.判断是否存在  isnot null,"",换行符等
        if (StrUtil.isNotBlank(json)) {
            //3.存在,直接返回
            R shop = JSONUtil.toBean(json,type);
            return shop;
        }
        //不等于空即为空字符串,isblank方法会将空字符串也判断为空值
        if (json!=null){
            //返回错误信息
            return null;
        }
        //4.不存在,根据id查询数据库(函数式编程 )
        R r =dbFallback.apply(id);
        //5.数据库中也不存在,返回错误
        if (r == null) {
            //将空值写入redis
            stringRedisTemplate.opsForValue().set(key,"",RedisConstants.CACHE_NULL_TTL ,TimeUnit.MINUTES);
            //返回错误信息
            return null;
        }
        //6.存在,写入redis
        this.set(key,r,time,unit);
        //7.返回
        return r;
    }

    //todo 线程池
    public static final ExecutorService CACHE_REBUILD_EXECUTOR= Executors.newFixedThreadPool(10);

    //TODO 4.逻辑过期解决缓存击穿
    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.判断是否存在  is null,"",换行符等
        //不考虑空值 原因是因为在redis里这个key是没有过期时间的,会一直存在,空值则说明其不是热点key,更不需要操作数据库。
        if (StrUtil.isBlank(json)) {
            return null;
        }
        //命中,需要先把json反序列化为对象
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        JSONObject data = (JSONObject) redisData.getData();
        R r=JSONUtil.toBean(data,type);
        LocalDateTime expireTime=redisData.getExpireTime();
        //判断是否过期
        if (expireTime.isAfter(LocalDateTime.now())) {
            //未过期,直接返回店铺信息
            return r;
        }
        //已过期,需要缓存重建:
        //获取互斥锁
        String lockKey=LOCK_SHOP_KEY+id;
        boolean isLock = tryLock(lockKey);
        //判断是否获取锁成功
        if (isLock){
            //成功,开启独立线程,实现缓存重建
            CACHE_REBUILD_EXECUTOR.submit(() ->{
                try {
                    //查询数据库
                    R r1 = dbFallBack.apply(id);
                    //写入redis
                    this.setWithLogical(key,r1,time,unit);

                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                //释放锁(弹幕:虽然已经设置了key到期时间,但若不释放锁,在锁未过期的时间里就都是旧数据?????)
                finally {
                    unLock(lockKey);
                }
            } );
        }
        //失败,返回过期的商铺信息
        return r;
    }

    //获取锁
    private boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        //调用工具类,因为拆箱过程中会有空值。因为Boolean可以是空值
        return BooleanUtil.isTrue(flag);
    }

    //释放锁
    private void unLock(String key){
        stringRedisTemplate.delete(key);
    }

}
1.将任意java对象序列化为json并储存在string类型的key中,并可设置TTL过期时间
public void set(String key, Object value, Long time, TimeUnit unit){
         stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value),time,unit);
    }
2.将任意java对象序列化为json并储存在key中,并可设置逻辑过期时间,处理缓存击穿
public void setWithLogical(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));
    }
3.根据key查询缓存,并反序列化为指定类型,利用缓存空值解决缓存穿透问题
 //缓存空值""解决缓存穿透
    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.判断是否存在  isnot null,"",换行符等
        if (StrUtil.isNotBlank(json)) {
            //3.存在,直接返回
            R shop = JSONUtil.toBean(json,type);
            return shop;
        }
        //不等于空即为空字符串,isblank方法会将空字符串也判断为空值
        if (json!=null){
            //返回错误信息
            return null;
        }
        //4.不存在,根据id查询数据库(函数式编程 )
        R r =dbFallback.apply(id);
        //5.数据库中也不存在,返回错误
        if (r == null) {
            //将空值写入redis
            stringRedisTemplate.opsForValue().set(key,"",RedisConstants.CACHE_NULL_TTL ,TimeUnit.MINUTES);
            //返回错误信息
            return null;
        }
        //6.存在,写入redis
        this.set(key,r,time,unit);
        //7.返回
        return r;
    }
4.根据key查询缓存,并反序列化为指定类型,利用逻辑过期解决缓存击穿问题
//TODO 4.逻辑过期解决缓存击穿
    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.判断是否存在  is null,"",换行符等
        //不考虑空值 原因是因为在redis里这个key是没有过期时间的,会一直存在,空值则说明其不是热点key,更不需要操作数据库。
        if (StrUtil.isBlank(json)) {
            return null;
        }
        //命中,需要先把json反序列化为对象
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        JSONObject data = (JSONObject) redisData.getData();
        R r=JSONUtil.toBean(data,type);
        LocalDateTime expireTime=redisData.getExpireTime();
        //判断是否过期
        if (expireTime.isAfter(LocalDateTime.now())) {
            //未过期,直接返回店铺信息
            return r;
        }
        //已过期,需要缓存重建:
        //获取互斥锁
        String lockKey=LOCK_SHOP_KEY+id;
        boolean isLock = tryLock(lockKey);
        //判断是否获取锁成功
        if (isLock){
            //成功,开启独立线程,实现缓存重建
            CACHE_REBUILD_EXECUTOR.submit(() ->{
                try {
                    //查询数据库
                    R r1 = dbFallBack.apply(id);
                    //写入redis
                    this.setWithLogical(key,r1,time,unit);

                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                //释放锁(弹幕:虽然已经设置了key到期时间,但若不释放锁,在锁未过期的时间里就都是旧数据?????)
                finally {
                    unLock(lockKey);
                }
            } );
        }
        //失败,返回过期的商铺信息
        return r;
    }

    //获取锁
    private boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        //调用工具类,因为拆箱过程中会有空值。因为Boolean可以是空值
        return BooleanUtil.isTrue(flag);
    }

    //释放锁
    private void unLock(String key){
        stringRedisTemplate.delete(key);
    }

//注意:测试该方法需保证其确实为热点key,即过期时间存在,故心在测试类中设置逻辑过期时间
@Test
    void testSaveShop() throws Exception {
        //shopService.saveShop2Redis(1L,10L);
        Shop shop = shopService.getById(1L);

        cacheClient.setWithLogical(CACHE_SHOP_KEY+1L,shop,10L, TimeUnit.SECONDS);
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值