JetCache防止缓存穿透

当get返回null的时候,无法断定是对应的key不存在,还是访问缓存发生了异常,所以JetCache针对部分操作提供了另外一套API,提供了完整的返回值,所以自己封装了一层,拿来即用

package com.wjh.auth.cache;

import com.alicp.jetcache.Cache;
import com.alicp.jetcache.CacheGetResult;
import com.alicp.jetcache.CacheResultCode;
import com.alicp.jetcache.MultiGetResult;
import com.wjh.auth.utils.JsonUtil;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Author even
 * @Description
 * @Date 2022/1/22 3:22 下午
 **/
@UtilityClass
@Slf4j
public class CacheHelper {
    /**
     * @param function DB获取数据
     */
    public static <K,V> V get(Cache<K,V> cache, Function<K,V> function, K obj){
        CacheGetResult<V> get = cache.GET(obj);
        if(get.isSuccess()){
            log.info("缓存里面获取到数据:key:{},value:{}",obj,get.getValue());
            return get.getValue();
        }
        V apply = function.apply(obj);
        log.info("DB里面获取到数据:key:{},value:{}",obj,apply);
        cache.put(obj,apply);
        return apply;
    }

    /**
     * @param function DB获取数据
     */
    public static <K,V> Map<K,V> getAll(Cache<K,V> cache, Function<Set<K>,Map<K,V>> function, Set<K> obj){
        log.info("CacheHelper查询的keys:{}",obj);
        MultiGetResult<K, V> kvMultiGetResult = cache.GET_ALL(obj);
        Map<K, CacheGetResult<V>> values = kvMultiGetResult.getValues();
        Set<K> noExistKeys = values.keySet().stream().filter(e ->noExists(values.get(e))).collect(Collectors.toSet());
        log.info("缓存里面没有获取到数据:keys:{}",noExistKeys);
        Map<K, V> noExistCache = function.apply(noExistKeys);
        log.info("DB里面获取到数据:keys:{},data:{}",noExistCache.keySet(), JsonUtil.toJson(noExistCache));
        Map<K, V> collect = new HashMap<>();
        noExistKeys.forEach(e->collect.put(e,null));
        collect.putAll(noExistCache);
        cache.putAll(collect);
        Map<K, V> result = values.keySet().stream().filter(k -> exists(values.get(k))).collect(Collectors.toMap(k -> k, k -> values.get(k).getValue()));
        log.info("CacheHelper查询的数据:keys:{},data:{}",result.keySet(), JsonUtil.toJson(result));
        result.putAll(noExistCache);
        return result;
    }

    private  <V> boolean  noExists(CacheGetResult<V> result){
       return CacheResultCode.NOT_EXISTS.equals(result.getResultCode()) || CacheResultCode.EXPIRED.equals(result.getResultCode());
    }

    private  <V> boolean  exists(CacheGetResult<V> result){
        return result.isSuccess() && result.getValue() != null;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值