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("CacheHelper没有获取到数据的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;
}
}
Java代码封装防止缓存穿透
最新推荐文章于 2024-09-27 00:45:01 发布
该博客主要介绍了如何利用JetCache库进行缓存管理,包括单个数据的获取和批量数据的处理。通过提供的`get`和`getAll`方法,实现了从缓存和数据库之间的无缝切换,当缓存中不存在数据时,会自动从数据库中获取并存入缓存,确保数据的实时性和一致性。同时,博客还展示了详细的日志记录,便于跟踪和调试。
摘要由CSDN通过智能技术生成