缓存在一个项目中使用的频率非常高,但是每个查询、存储很相似,每次需要使用缓存都写一遍,造成代码冗余及资源浪费,封装通用工具就很有必要了。
一、Redis 存储工具- 将任意Java对象序列化为json并存储在string类型的key中,并且可以设置TTL过期时间
- 将任意Java对象序列化为json并存储在string类型的key中,并且可以设置逻辑过期时间,用于处理缓存击穿问题
- 根据指定的key查询缓存,并反序列化为指定类型,利用缓存空值的方式解决缓存穿透问题
- 根据指定的key查询缓存,并反序列化为指定类型,需要利用逻辑过期解决缓存击穿问题
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
@Slf4j
@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) {
stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), time, unit);
}
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)));
// 写入redis
stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData), time, unit);
}
public R queryWithPassThrough(String keyPrefix, ID id, Class type, Function dbFallback
, Long time, TimeUnit unit) {
String key = keyPrefix + id;
// 1.从redis查询缓存数据
String json = stringRedisTemplate.opsForValue().get(key);
// 2.判断是否存在
if (StrUtil.isNotBlank(json)) {
// 3.存在。直接返回
return JSONUtil.toBean(json, type);
}
//4.判断命中的是否是空值,解决缓存穿透
if (json != null) {
return null;
}
// 5.不存在,查询数据库
R r = dbFallback.apply(id);
// 6.不存在,返回错误数据
if (r == null) {
stringRedisTemplate.opsForValue().set(key, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
return null;
}
// 7.存在,写入Redis
this.set(key, r, time, unit);
return r;
}
private boolean trylock(String key) {
//setIfAbsent方法和命令行的setnx命令是一样的,并发执行setIfAbsent,只有第一个线程能成功,其余线程都会失败
Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.MINUTES);
// 此处使用hutool包的工具,防止直接返回flag,造成拆箱时空指针问题。
return BooleanUtil.isTrue(flag);
}
private void unlock(String key) {
stringRedisTemplate.delete(key);
}
private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);
public R queryWithLogiCalExpire(String keyPrefix, ID id, Class type, Function dbFallback, Long time, TimeUnit unit) {
String key = keyPrefix + id;
// 1.从redis查询商铺缓存
String json = stringRedisTemplate.opsForValue().get(key);
//2.判断值是否存在
if (StrUtil.isBlank(json)) {
//3.为空直接返回null
return null;
}
// 4.命中把json反序列化成对象
RedisData redisData = JSONUtil.toBean(json, RedisData.class);
R r = JSONUtil.toBean((JSONObject) redisData.getData(), type);
LocalDateTime expireTime = redisData.getExpireTime();
// 5.判断是否过期,过期时间是否在当前时间之后
if (expireTime.isAfter(LocalDateTime.now())) {
// 5.1 未过期返回店铺信息
return r;
}
// 5.2 过期,需要重建缓存
// 6.1获取锁
String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
// 此处获取锁方式和互斥锁实现方式一致
boolean isLock = trylock(lockKey);
// 6.2 判断获取锁是否成功
if (isLock) {
// 7.开启一个独立的线程来执行重建
CACHE_REBUILD_EXECUTOR.submit(() -> {
try {
// 7.1查询数据库
R r1 = dbFallback.apply(id);
// 7.2写入redis
this.setWithLogicalExpire(key, r1, time, unit);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
//7.3 释放锁, 此处释放锁方式和互斥锁实现方式一致
unlock(lockKey);
}
});
}
//先返回旧的数据
return r;
}
}
使用工具类查询
@Resource
private CacheClient cacheClient;
@Override
public Result queryShopById(Long id) {
//使用工具类,解决缓存穿透
Shop shop = cacheClient.queryWithPassThrough(RedisConstants.CACHE_SHOP_KEY, id, Shop.class,
id2 -> getById(id2), RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
//使用工具类,解决缓存击穿
Shop shop1 = cacheClient.queryWithLogiCalExpire(RedisConstants.CACHE_SHOP_KEY, id, Shop.class,
this::getById, RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
if (shop == null) {
Result.fail("店铺信息不存在!");
}
return Result.ok(shop);
}
@Resource
private CacheClient cacheClient;
@Override
public Result queryShopById(Long id) {
//使用工具类,解决缓存穿透
Shop shop = cacheClient.queryWithPassThrough(RedisConstants.CACHE_SHOP_KEY, id, Shop.class,
id2 -> getById(id2), RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
//使用工具类,解决缓存击穿
//Shop shop = cacheClient.queryWithLogiCalExpire(RedisConstants.CACHE_SHOP_KEY, id, Shop.class,
// this::getById, RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
// 互斥锁实现方式
//Shop shop = queryWithMutex(id);
// 逻辑过期实现方式
//Shop shop = queryWithLogiCalExpire(id);
if (shop == null) {
Result.fail("店铺信息不存在!");
}
return Result.ok(shop);
}



