Java代码封装防止缓存穿透

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  V get(Cache cache, Function function, K obj){
        CacheGetResult 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  Map getAll(Cache cache, Function,Map> function, Set obj){
        log.info("CacheHelper查询的keys:{}",obj);
        MultiGetResult kvMultiGetResult = cache.GET_ALL(obj);
        Map> values = kvMultiGetResult.getValues();
        Set noExistKeys = values.keySet().stream().filter(e ->noExists(values.get(e))).collect(Collectors.toSet());
        log.info("CacheHelper没有获取到数据的keys:{}",noExistKeys);
        Map noExistCache = function.apply(noExistKeys);
        log.info("DB获取到数据的keys:{},data:{}",noExistCache.keySet(), JsonUtil.toJson(noExistCache));
        Map collect = new HashMap<>();
        noExistKeys.forEach(e->collect.put(e,null));
        collect.putAll(noExistCache);
        cache.putAll(collect);
        Map 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   boolean  noExists(CacheGetResult result){
       return CacheResultCode.NOT_EXISTS.equals(result.getResultCode()) || CacheResultCode.EXPIRED.equals(result.getResultCode());
    }

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

你可能感兴趣的:(java,缓存,postman)