【Redis】缓存工具封装
文章目录
- 【Redis】缓存工具封装
- 1. 方法要求
- 1.1 方法一
- 1.2 方法二
- 1.3 方法三
- 1.4 方法四
- 2. 完整工具类代码
将
StringRedisTemplate
封装成一个缓存工具类,方便以后重复使用。
1. 方法要求
在这个工具类中我们完成四个方法:
- 方法①:将任意Java对象序列化为json并存储在string类型的key中,并且可以设置TTL过期时间
- 方法②:将任意Java对象序列化为json并存储在string类型的key中,并且可以设置逻辑过期时间,用于处理缓存击穿问题
- 方法③:根据指定的key查询缓存,并反序列化为指定类型,利用缓存空值的方式解决缓存穿透问题
- 方法④:根据指定的key查询缓存,并反序列化为指定类型,需要利用逻辑过期解决缓存击穿问题
我们新建一个类,先把大致框架写出来,方法的参数可以边写边完善,但是我的方法参数已经完善好了:
@Component
public class CacheClient {private final StringRedisTemplate stringRedisTemplate;public CacheClient(StringRedisTemplate stringRedisTemplate) {this.stringRedisTemplate = stringRedisTemplate;}//方法一public void set(String key, Object value, Long time, TimeUnit unit) {}//方法二public void setWithLogicExpire(String key, Object value, Long time, TimeUnit unit) {}//方法三public <R, ID> R queryWithPassThrough(String keyPrefix, ID id, Class<R> type,Long time, TimeUnit unit, Function<ID, R> dbFallback) {}//方法四public <R, ID> R queryWithLogicalExpire(String prefix, ID id, String lockPre, Class<R> type,Long time, TimeUnit unit, Function<ID, R> dbFallback) {}//线程池private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);//获取锁private boolean tryLock(String key) {Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", LOCK_SHOP_TTL, TimeUnit.SECONDS);return BooleanUtil.isTrue(flag);}//释放锁private void unLock(String key) {stringRedisTemplate.delete(key);}
}
接下来我们可以不断完善这些方法。
1.1 方法一
public void set(String key, Object value, Long time, TimeUnit unit) {stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), time, unit);
}
1.2 方法二
public void setWithLogicExpire(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));
}
1.3 方法三
public <R, ID> R queryWithPassThrough(String keyPrefix, ID id, Class<R> type,Long time, TimeUnit unit, Function<ID, R> dbFallback) {String key = keyPrefix + id;//1.从redis中查询商铺缓存String json = stringRedisTemplate.opsForValue().get(key);//2.判断是否存在if (StrUtil.isNotBlank(json)) {//2.1.存在return JSONUtil.toBean(json, type);}//2.2.不存在//判断是否为空值if (json != null) {//不为null,则必为空return null;}//3.查询数据库R r = dbFallback.apply(id);if (r == null) {//3.1.不存在,缓存空值stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);} else {//3.2.存在,缓存数据this.set(key, r, time, unit);}return r;
}
方法三用到了函数式编程,这里非常巧妙,顺便再贴一下调用方法是怎样调用的:
Shop shop = cacheClient.queryWithPassThrough(CACHE_SHOP_KEY,id,Shop.class,CACHE_SHOP_TTL,TimeUnit.MINUTES,this::getById);
1.4 方法四
public <R, ID> R queryWithLogicalExpire(String prefix, ID id, String lockPre, Class<R> type,Long time, TimeUnit unit, Function<ID, R> dbFallback) {//1.从redis查询商铺缓存String key = prefix + id;String json = stringRedisTemplate.opsForValue().get(key);//2.判断是否存在if (StrUtil.isBlank(json)) {//未命中,直接返回空return null;}//3.命中,判断是否过期RedisData redisData = JSONUtil.toBean(json, RedisData.class);R r = JSONUtil.toBean((JSONObject) redisData.getData(), type);if (redisData.getExpireTime().isAfter(LocalDateTime.now())) {//3.1未过期,直接返回店铺信息return r;}//3.2.已过期,缓存重建//3.3.获取锁String lockKey = lockPre + id;boolean flag = tryLock(lockKey);if (flag) {//3.4.获取成功//4再次检查redis缓存是否过期,做double checkjson = stringRedisTemplate.opsForValue().get(key);//4.1.判断是否存在if (StrUtil.isBlank(json)) {//未命中,直接返回空return null;}//4.2.命中,判断是否过期redisData = JSONUtil.toBean(json, RedisData.class);r = JSONUtil.toBean((JSONObject) redisData.getData(), type);if (redisData.getExpireTime().isAfter(LocalDateTime.now())) {//4.3.未过期,直接返回店铺信息return r;}//4.4过期,返回旧数据CACHE_REBUILD_EXECUTOR.submit(() -> {//5.重建缓存try {R r1 = dbFallback.apply(id);this.setWithLogicExpire(key, r1, time, unit);} catch (Exception e) {throw new RuntimeException(e);} finally {//释放锁unLock(lockKey);}});}//7.获取失败,返回旧数据return r;
}
2. 完整工具类代码
@Component
@Slf4j
public class CacheClient {private final StringRedisTemplate stringRedisTemplate;public CacheClient(StringRedisTemplate stringRedisTemplate) {this.stringRedisTemplate = stringRedisTemplate;}public void set(String key, Object value, Long time, TimeUnit unit) {stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), time, unit);}public void setWithLogicExpire(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));}public <R, ID> R queryWithPassThrough(String keyPrefix, ID id, Class<R> type,Long time, TimeUnit unit, Function<ID, R> dbFallback) {String key = keyPrefix + id;//1.从redis中查询商铺缓存String json = stringRedisTemplate.opsForValue().get(key);//2.判断是否存在if (StrUtil.isNotBlank(json)) {//2.1.存在return JSONUtil.toBean(json, type);}//2.2.不存在//判断是否为空值if (json != null) {//不为null,则必为空return null;}//3.查询数据库R r = dbFallback.apply(id);if (r == null) {//3.1.不存在,缓存空值stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);} else {//3.2.存在,缓存数据this.set(key, r, time, unit);}return r;}public <R, ID> R queryWithLogicalExpire(String prefix, ID id, String lockPre, Class<R> type,Long time, TimeUnit unit, Function<ID, R> dbFallback) {//1.从redis查询商铺缓存String key = prefix + id;String json = stringRedisTemplate.opsForValue().get(key);//2.判断是否存在if (StrUtil.isBlank(json)) {//未命中,直接返回空return null;}//3.命中,判断是否过期RedisData redisData = JSONUtil.toBean(json, RedisData.class);R r = JSONUtil.toBean((JSONObject) redisData.getData(), type);if (redisData.getExpireTime().isAfter(LocalDateTime.now())) {//3.1未过期,直接返回店铺信息return r;}//3.2.已过期,缓存重建//3.3.获取锁String lockKey = lockPre + id;boolean flag = tryLock(lockKey);if (flag) {//3.4.获取成功//4再次检查redis缓存是否过期,做double checkjson = stringRedisTemplate.opsForValue().get(key);//4.1.判断是否存在if (StrUtil.isBlank(json)) {//未命中,直接返回空return null;}//4.2.命中,判断是否过期redisData = JSONUtil.toBean(json, RedisData.class);r = JSONUtil.toBean((JSONObject) redisData.getData(), type);if (redisData.getExpireTime().isAfter(LocalDateTime.now())) {//4.3.未过期,直接返回店铺信息return r;}//4.4过期,返回旧数据CACHE_REBUILD_EXECUTOR.submit(() -> {//5.重建缓存try {R r1 = dbFallback.apply(id);this.setWithLogicExpire(key, r1, time, unit);} catch (Exception e) {throw new RuntimeException(e);} finally {//释放锁unLock(lockKey);}});}//7.获取失败,返回旧数据return r;}private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);//获取锁private boolean tryLock(String key) {Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", LOCK_SHOP_TTL, TimeUnit.SECONDS);return BooleanUtil.isTrue(flag);}//释放锁private void unLock(String key) {stringRedisTemplate.delete(key);}
}