1.将任意Java对象序列化为json并存储在string类型的key中,并且可以设置TTL过期时间
//将任意对象缓存并设置过期时间
public void set(String key, Object value, Long time, TimeUnit unit) {
stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), time, unit);
}
,2.将任意Java对象序列化为json并存储在string类型的key中,并且可以设置逻辑过期时间用于处理缓存击穿问题
@Data
public class RedisData {
private LocalDateTime expireTime;
private Object data;
}
//将任意对象缓存并设置逻辑过期时间
public void setWithLogicalExpire(String key, Object value, Long time, TimeUnit unit) {
//设置逻辑过期
RedisData redisData = new RedisData();
redisData.setData(value);
redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
}
3.根据指定的key查询缓存,并反序列化为指定类型,利用缓存空值的方式解决缓存穿透问题
//取出数据并解决缓存穿透问题
public <R, ID> R queryWithPassThrough(
String key, ID id, Class<R> type, Function<ID, R> dbFallback, Long time, TimeUnit unit) {
String json = stringRedisTemplate.opsForValue().get(key);
//存在则返回
if (StrUtil.isNotBlank(json)) {
return JSONUtil.toBean(json, type);
}
//判断是否命中空值
if (json.equals("")) {
return null;
}
//不存在则根据id查询数据库
R apply = dbFallback.apply(id);
if (apply == null) {
//缓存空数据
stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
}
//不为空则缓存数据
this.set(key, apply, time, unit);
return apply;
}
用法.调用:
//解决缓存穿透
cacheClient.queryWithPassThrough(CACHE_SHOP_KEY,id,Shop.class,this::getById,CACHE_SHOP_TTL,TimeUnit.MINUTES);
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/105063.html