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;
    }
}


版权声明:本文为Man20161217原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。