目录
什么是缓存击穿
缓存击穿问题也叫热点Key问题,就是一个被高并发访问并且缓存重建业务较复杂的key突然失效了,无数的请求访问会在瞬间给数据库带来巨大的冲击。
怎么解决 ?
方案一:互斥锁
思维导图
业务逻辑
业务代码
package com.example.demo.controller;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.example.demo.entity.Shop;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.TimeUnit;
@RestController
public class RedisTestController {
@Autowired
private StringRedisTemplate stringRedisTemplate;
/**
* 获取锁
* @param key
* @return
*/
private boolean tryLock(String key) {
//设置过期时间防止死锁(锁的有效期比正常执行完业务的实际长10倍20倍,避免异常情况)
Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.MINUTES);
// 直接返回会做拆箱,有可能返回空指针,所以使用工具类
return BooleanUtil.isTrue(flag);
}
/**
* 释放锁
* @param key
*/
private void unLock(String key) {
stringRedisTemplate.delete(key);
}
/**
* 互斥锁解决缓存击穿
*
* @param id
* @return
*/
@PostMapping("/mutex")
public Object queryWithMutex(@RequestBody String id) {
String key = "shop:" + id;
//1.从redis中查询信息
String shopJson = stringRedisTemplate.opsForValue().get(key);
//2.判断是否存在
if (StrUtil.isNotBlank(shopJson)) {
//3.存在,直接返回
return JSONUtil.toBean(shopJson, Shop.class);
}
//判断命中是否是空值""
//等价于 if ("".equals(shopJson))
if (shopJson != null) {
//返回一个错误信息
return "店铺信息不存在";
}
//4.实现缓存重建
//4.1.获取互斥锁
String lockKey = "lock:shop:" + id;
Shop shop = null;
try {
boolean isLock = tryLock(lockKey);
//4.2.判断是否获取成功
if (!isLock) {
//4.3.失败,则休眠并重试
Thread.sleep(50);
return queryWithMutex(id);
}
//4.4.成功,根据id查询数据库
//获取锁之后,查询数据库之前应该再次检测redis缓存是否存在做DoubleCheck。
//如果存在则无需重建缓存
//①.从redis中查询信息
shopJson = stringRedisTemplate.opsForValue().get(key);
//②.判断是否存在
if (StrUtil.isNotBlank(shopJson)) {
//③.存在,直接返回
return JSONUtil.toBean(shopJson, Shop.class);
}
//判断命中是否是空值""
//等价于 if ("".equals(shopJson))
if (shopJson != null) {
//返回一个错误信息
return "店铺信息不存在";
}
//模拟从数据库中取值取到空值(验证解决缓存穿透问题)
System.out.println("=================开始连接数据库=================");
if ("1".equals(id)) {
shop = new Shop();
shop.setName("苹果");
shop.setPrice("4999");
}
//模拟重建的延时(验证并发时分布锁的作用)
Thread.sleep(200);
//5.不存在,返回错误
if (shop == null) {
//将空值缓存到redis
stringRedisTemplate.opsForValue().set(key, "", 2L, TimeUnit.MINUTES);
//返回错误信息
return "店铺不存在!";
}
//6.存在写入redis中
stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), 5, TimeUnit.MINUTES);
} catch (InterruptedException e) {
return new RuntimeException(e);
} finally {
//7.释放互斥锁
unLock(lockKey);
}
//8.返回
return shop;
}
}
代码测试
请求的结果全部查询到
qps:197.5/sec
对数据库的查询只有一次 ,证明在高并发的情况下,所有的请求并不是全打入数据库,只有一个
优点缺点
优点:
1.没有额外的内存消耗(相对于逻辑过期来说,多维护一个过期自动)
2.保证一致性
3.实现简单
缺点:
1.线程需要等待,性能受影响
2.可能有死锁风险(通过锁过期解决)
死锁产生原因:假设业务有多个缓存查询的需求,另外一个业务也有,你拿一把锁,获取另外一边锁的时候在其他业务里。
方案二:逻辑过期
思维导图
业务逻辑
业务代码
不存在未命中情况,key是不会过期,一旦添加缓存中应该是永久存在,热点一般是参加活动的商品,一般提前加入缓存中,直到活动结束。未命中不用考虑穿透解决方案
提前进行缓存
package com.example.demo;
import cn.hutool.json.JSONUtil;
import com.example.demo.entity.Shop;
import com.example.demo.utils.RedisBloomUtils;
import com.example.demo.utils.RedisData;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import java.time.LocalDateTime;
@Slf4j
@SpringBootTest
class DemoApplicationTests {
@Autowired
private RedisBloomUtils redisBloomUtils;
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Test
void cache(){
System.out.println("=================开始连接数据库=================");
String id = "1";
Shop shop = null;
if ("1".equals(id)) {
shop = new Shop();
shop.setName("苹果");
shop.setPrice("4999");
}
//② 封装逻辑过期时间
RedisData redisData = new RedisData();
redisData.setData(shop);
redisData.setExpireTime(LocalDateTime.now().plusSeconds(20L));
stringRedisTemplate.opsForValue().set( "shop:" + id, JSONUtil.toJsonStr(redisData));
}
}
编写逻辑过期代码,因为不存在未命中情况,key是不会过期,一般都是提前准备好的,如果为空,直接返回空,便于测试id为1的缓存名字修改为华为。
package com.example.demo.controller;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.example.demo.entity.Shop;
import com.example.demo.utils.RedisData;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
@RestController
public class RedisTestController {
@Autowired
private StringRedisTemplate stringRedisTemplate;
private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);
/**
*
* 逻辑过期解决缓存击穿
* @param id
* @return
*/
@PostMapping("/expire")
public Object queryWithLogicalExpire(@RequestBody String id) {
String key = "shop:" + id;
//1.从redis中查询信息
String shopJson = stringRedisTemplate.opsForValue().get(key);
//2.判断是否存在
if (StrUtil.isBlank(shopJson)) {
//3.不存在,直接返回
return null;
}
//4.命中,需要先把json反序列化为对象
RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
Shop shop = JSONUtil.toBean((JSONObject)redisData.getData(),Shop.class);
LocalDateTime expireTime = redisData.getExpireTime();
//5.判断是否过期
if(expireTime.isAfter(LocalDateTime.now())){
//5.1未过期,直接返回店铺信息
return shop;
}
//5.2.已过期,需要缓存重建
//6.缓存重建
//6.1.获取互斥锁
String lockKey = "lock:shop:"+id;
boolean isLock = tryLock(lockKey);
//6.2.判断是否获取锁成功
if (isLock) {
//注意:获取锁成功应该再次检测redis缓存是否过期,做DoubleCheck。
//如果存在则无需重建缓存
//6.3成功,开启独立线程,实现缓存重建
CACHE_REBUILD_EXECUTOR.submit(()->{
//重建缓存
try {
//①.查询店铺数据
//模拟从数据库中取值取到空值(验证解决缓存穿透问题)
System.out.println("=================开始连接数据库=================");
Shop shop1 = null;
if ("1".equals(id)) {
shop1 = new Shop();
shop1.setName("华为");
shop1.setPrice("4999");
}
//便于测试
Thread.sleep(200);
//② 封装逻辑过期时间
RedisData redisData1 = new RedisData();
redisData1.setData(shop1);
redisData1.setExpireTime(LocalDateTime.now().plusSeconds(20L));
stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData1));
} catch (Exception e) {
throw new RuntimeException();
} finally {
//释放锁
unLock(lockKey);
}
});
}
//6.4.返回过期的商铺信息
return shop;
}
}
代码测试
第一次查询还是名字为苹果的旧缓存,200ms后可跟新为新缓存
第六次查询时是名字为华为的新内存
对数据库的查询只有一次 ,证明在高并发的情况下,所有的请求并不是全打入数据库,只有一个
优点缺点
优点:
1.线程无需等待
2.性能较好
缺点:
1.不保证一致性
2.有额外内存消耗
3.实现复杂