缓存在提升系统性能的同时,也会面临缓存击穿和缓存穿透等常见问题。为了解决这些问题,我们可以使用缓存工具类来进行优化处理。下面介绍如何使用缓存工具类来解决缓存击穿和缓存穿透问题。
缓存工具类介绍
在这里我们以一个名为 CacheClient
的缓存工具类为例,该类封装了操作 Redis 的方法,能够实现设置缓存、查询缓存并处理缓存击穿、缓存穿透等问题。
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.entity.Shop;
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;
import static com.hmdp.utils.RedisConstants.*;
@Component
@Slf4j
public class CacheClient {
private StringRedisTemplate stringRedisTemplate;
private static final ExecutorService CACHE_REBUILD_EXECUTOR= Executors.newFixedThreadPool(10);
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.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
redisData.setData(value);
stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
}
//TODO 解决缓存穿透缓存穿透
public <R,ID> R queryWithPassThrough(String keyPrefix, ID id, Class<R> type, Function<ID,R> dbFallback,
Long time, TimeUnit unit){
//1.查询缓存
String key=keyPrefix + id;
String json= stringRedisTemplate.opsForValue().get(key);
if(StrUtil.isNotBlank(json)){
return JSONUtil.toBean(json,type);
}
//判断命中的是否是空值
if(json!=null){
return null;
}
R r=dbFallback.apply(id);
if(r==null){
//将空值写入redis
stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL,TimeUnit.MINUTES);
return null;
}
this.set(key,r,time,unit);
return r;
}
//TODO 解决缓存击穿--逻辑过期
public <R,ID> R queryWithLogicalExpire(String keyPrefix,ID id,Class<R> type,Function<ID,R> dbFallback,
Long time, TimeUnit unit){
//1.查询缓存
String key=CACHE_SHOP_KEY + id;
String json= stringRedisTemplate.opsForValue().get(key);
if(StrUtil.isBlank(json)){
return null;
}
//命中,把json反序列化为对象
RedisData redisData = JSONUtil.toBean(json, RedisData.class);
R r = JSONUtil.toBean((JSONObject) redisData.getData(), type);
LocalDateTime expireTime=redisData.getExpireTime();
//判断是否过期
if(expireTime.isAfter(LocalDateTime.now())){
//未过期,直接返回店铺信息
return r;
}
//已过期,缓存重建
String lockKey=LOCK_SHOP_KEY+id;
boolean isLock = tryLock(lockKey);
if(isLock){
// 再次检查数据是否过期
String shopJson2=stringRedisTemplate.opsForValue().get(key);
if(StrUtil.isBlank(json)){
return null;
}
redisData = JSONUtil.toBean(json, RedisData.class);
expireTime=redisData.getExpireTime();
if(expireTime.isAfter(LocalDateTime.now())){
//未过期,直接返回店铺信息
return JSONUtil.toBean((JSONObject)redisData.getData(),type);
}
//再次检查数据依然过期
// 开启独立线程
CACHE_REBUILD_EXECUTOR.submit(()->{
try {
R r1 = dbFallback.apply(id);
Thread.sleep(300);
this.setWithLogicalExpire(key,r1,time,unit);
}catch (Exception e){
throw new RuntimeException(e);
}finally {
//释放锁
unlock(lockKey);
}
});
}
//返回过期数据
return r;
}
//获取锁
private boolean tryLock(String key){
Boolean flag=stringRedisTemplate.opsForValue().setIfAbsent(key,"1",LOCK_SHOP_TTL,TimeUnit.MINUTES);
return BooleanUtil.isTrue(flag);
}
//释放锁
private void unlock(String key){
stringRedisTemplate.delete(key);
}
}
解决缓存穿透问题
缓存穿透是指查询一个不存在的数据,由于缓存层无法命中,导致请求直接访问数据库,这会对系统造成额外负担。为了解决缓存穿透问题,我们可以通过以下方法:
// 处理缓存穿透
public <R,ID> R queryWithPassThrough(String keyPrefix, ID id, Class<R> type, Function<ID,R> dbFallback,
Long time, TimeUnit unit){
String key = keyPrefix + id;
String json = stringRedisTemplate.opsForValue().get(key);
if(StrUtil.isNotBlank(json)){
return JSONUtil.toBean(json, type);
}
if(json != null){
return null;
}
R r = dbFallback.apply(id);
if(r == null){
stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
return null;
}
this.set(key, r, time, unit);
return r;
}
在 queryWithPassThrough
方法中,首先尝试从缓存中获取数据,如果未命中则查询数据库,如果数据库中也没有数据,则将空值写入缓存。
解决缓存击穿问题
缓存击穿是指热点数据在缓存失效后被大量请求同时访问,导致请求直接访问数据库。为了解决缓存击穿问题,我们可以通过逻辑过期和锁机制来提高缓存效率,具体实现如下:
// 处理缓存击穿--逻辑过期
public <R,ID> R queryWithLogicalExpire(String keyPrefix, ID id, Class<R> type, Function<ID,R> dbFallback,
Long time, TimeUnit unit){
String key = CACHE_SHOP_KEY + id;
String json = stringRedisTemplate.opsForValue().get(key);
if(StrUtil.isBlank(json)){
return null;
}
RedisData redisData = JSONUtil.toBean(json, RedisData.class);
R r = JSONUtil.toBean((JSONObject) redisData.getData(), type);
LocalDateTime expireTime = redisData.getExpireTime();
if(expireTime.isAfter(LocalDateTime.now())){
return r;
}
String lockKey = LOCK_SHOP_KEY + id;
boolean isLock = tryLock(lockKey);
if(isLock){
// 重新检查数据是否过期
String shopJson2 = stringRedisTemplate.opsForValue().get(key);
if(StrUtil.isBlank(json)){
return null;
}
redisData = JSONUtil.toBean(json, RedisData.class);
expireTime = redisData.getExpireTime();
if(expireTime.isAfter(LocalDateTime.now())){
return JSONUtil.toBean((JSONObject) redisData.getData(), type);
}
// 开启独立线程进行缓存重建
CACHE_REBUILD_EXECUTOR.submit(() -> {
try {
R r1 = dbFallback.apply(id);
Thread.sleep(300);
this.setWithLogicalExpire(key, r1, time, unit);
} catch (Exception e){
throw new RuntimeException(e);
} finally {
unlock(lockKey);
}
});
}
return r;
}
在 queryWithLogicalExpire
方法中,首先判断缓存是否过期,如果过期则尝试获取锁,通过锁机制保证只有一个线程重新构建缓存,并设置逻辑过期时间,避免缓存击穿问题。
通过以上的优化,我们可以有效解决缓存击穿和缓存穿透问题,提高系统的性能和稳定性。
希望以上内容对您有所帮助,更多技术分享请关注我的CSDN博客。