81,090
社区成员
发帖
与我相关
我的任务
分享
/**
* 获取缓存,不存在时调用方法进行填充
* @param key 缓存key
* @param cacheSecond 缓存时长,单位秒
* @param fillWhileNoFound 缓存不存在时的数据获取方法,用于填充缓存
* @param <T> 缓存数据类型
* @return 缓存数据
* @throws Exception 方法的异常
*/
public static<T> T getCache(String key, int cacheSecond, Callable fillWhileNoFound) throws Exception {
Object ret = redis.opsForValue().get(key);
if (ret != null)
return (T) ret;
try {
ret = fillWhileNoFound.call();
if (ret == null) {
return null;
}
}catch (Exception exp){
log.error(exp.toString());
}
redis.opsForValue().set(key, ret, Duration.ofSeconds(cacheSecond));
return (T) ret;
}