黑马Redis实战项目——黑马点评笔记03 | 商户查询缓存——缓存基础知识
1、什么是缓存,优缺点
2、添加Redis缓存
2.1、添加商户信息到Redis缓存
//ShopController方法
@GetMapping("/{id}")
public Result queryShopById(@PathVariable("id") Long id) {
return shopService.queryById(id);
}
//接口定义queryById方法
Result queryById(Long id);
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
@Resource
private StringRedisTemplate stringRedisTemplate;
@Override
public Result queryById(Long id) {
String key = RedisConstants.CACHE_SHOP_KEY+id;
//1 从redis查询商户缓存
String shopJson = stringRedisTemplate.opsForValue().get(key);
//2 判断是否存在
if(StrUtil.isNotBlank(shopJson)){
//3 存在,直接返回
Shop shop = JSONUtil.toBean(shopJson, Shop.class);
return Result.ok(shop);
}
//4 不存在,根据id查询数据库
Shop shop = getById(id);
//5 数据库不存在,返回错误
if(shop==null){
return Result.fail("店铺不存在!");
}
//6 数据库存在,将数据写入redis并返回
stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop));
return Result.ok(shop);
}
}
2.2、作业,添加商户分类到redis缓存
商户分类列表是不变动的,因此我们可以将它存入缓存中,避免每次访问时都去查询数据库
查询数据库返回的是List类型数据,这里使用Redisd 的 List数据类型。
//ShopTypeController类方法修改
@GetMapping("list")
public Result queryTypeList() {
return typeService.queryShopType();
}
//接口定义queryShopType方法
Result queryShopType();
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
@Resource
private StringRedisTemplate stringRedisTemplate;
@Override
public Result queryShopType() {
// 1 从 Redis 中查询商铺缓存
List<String> shopTypeList = stringRedisTemplate.opsForList().range(RedisConstants.CACHE_SHOP_TYPE_LIST_KEY, 0, -1);
// 2 判断 Redis 中是否有该缓存
if(shopTypeList!=null && !shopTypeList.isEmpty()){
// 3若 Redis 中存在该缓存,将JSON转为对象返回客户端
List<ShopType> typeList = shopTypeList.stream().map((shopTypeJson)->{
ShopType shopType = JSONUtil.toBean(shopTypeJson, ShopType.class);
return shopType;
}).collect(Collectors.toList());
return Result.ok(typeList);
}
// 4Redis 中若不存在该数据,则从数据库中查询
List<ShopType> typeList = query().orderByAsc("sort").list();
// 5 判断数据库中是否存在
if (typeList == null || typeList.isEmpty()) {
// 6 数据库中也不存在,则返回 false
return Result.fail("分类不存在!");
}
// 7 数据库中存在,则将查询到的信息存入 Redis
for (ShopType shopType : typeList) {
stringRedisTemplate.opsForList().rightPushAll(RedisConstants.CACHE_SHOP_TYPE_LIST_KEY, JSONUtil.toJsonStr(shopType));
}
// 8 返回
return Result.ok(typeList);
}
}
3、缓存更新策略
3.1、理论
三种主动更新策略选择:
cache aside pattern设计:
因为操作数据库的时间长,这期间缓存被查的概率高,容易发生线程查到的数据不一致的问题,因此在操作数据库之后删除缓存更不容易出问题。
总结:缓存更新的最佳实践方案
3.2、实践
1、查询时设置超时时间(超时剔除)
ShopServiceImpl类的queryById方法中
//6 数据库存在,将数据写入redis并返回(添加超时时间)
stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL, TimeUnit.MINUTES);
2、修改店铺时,先修改数据库再删除缓存
//ShopController中updateShop方法
@PutMapping
public Result updateShop(@RequestBody Shop shop) {
// 写入数据库
return shopService.update(shop);
}
//IShopService中定义方法
Result update(Shop shop);
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
@Resource
private StringRedisTemplate stringRedisTemplate;
/**
* 更新商铺信息
* @param shop
* @return
*/
@Override
@Transactional//保证(操作数据库和删除缓存)的原子性
public Result update(Shop shop) {
Long id = shop.getId();
if(id == null){
return Result.fail("店铺id不能为空");
}
//1 更新数据库
updateById(shop);
//2 删除缓存
stringRedisTemplate.delete(CACHE_SHOP_KEY+shop.getId());
return Result.ok();
}
}
4、缓存穿透
4.1、理论
缓存穿透及两种解决方案:
4.2、实践(缓存null值)
实现逻辑:
1、将空值写入字符串
//ShopServiceImpl 类中queryById方法修改
//5 数据库不存在,返回错误
if(shop==null){
//将空值写入Redis
stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL, TimeUnit.MINUTES);
//返回错误信息
return Result.fail("店铺不存在!");
}
2、判断从缓存中取出的是否为空值
//ShopServiceImpl 类中queryById方法查询redis失败后添加此段代码
// 判断命中的是否为空值,如果不为null则为空字符串""
if(shopJson!=null){
return Result.fail("店铺信息不存在");
}
4.3、总结
5、缓存雪崩
5.1、理论
5、缓存击穿(热点Key问题)
5.1、理论
什么是缓存击穿
两种解决方案:互斥锁、逻辑过期
两种解决方案的优缺点
5.2、实践
A.基于互斥锁实现
当前互斥锁可以使用redis的 SETNX 命令实现。
1、声明方法表示获取锁和释放锁
//ShopServiceImpl 类中声明方法表示获取锁和释放锁
//获取锁
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);
}
2、缓存命中后获取互斥锁逻辑
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
@Resource
private StringRedisTemplate stringRedisTemplate;
/**
* 根据id查询商铺信息
* @param id
* @return
*/
@Override
public Result queryById(Long id) {
//缓存穿透
//Shop shop = queryWithPassThrough(id);
//互斥锁解决缓存击穿
Shop shop = queryWithMutex(id);
if (shop == null) {
return Result.fail("店铺不存在!");
}
//返回
return Result.ok(shop);
}
/**
* 互斥锁解决缓存击穿
* @param id
* @return
*/
public Shop queryWithMutex(Long id){
String key = CACHE_SHOP_KEY+id;
//1 从redis查询商户缓存
String shopJson = stringRedisTemplate.opsForValue().get(key);
//2 判断是否存在
if(StrUtil.isNotBlank(shopJson)){
//3 存在,直接返回
Shop shop = JSONUtil.toBean(shopJson, Shop.class);
return shop;
}
// 判断命中的是否为空值,如果不为null则为空字符串""
if(shopJson!=null){
return null;
}
//A 实现缓存重建
//A1 获取互斥锁
String lockKey = LOCK_SHOP_KEY+id;
Shop shop = null;
try {
boolean isLock = tryLock(lockKey);
//A2 判断是否成功
if(!isLock){
//A3 失败,休眠后重试
Thread.sleep(50);
return queryWithMutex(id);
}
//A4 获取成功,再次检测redis缓存是否存在,如存在则无需创建,不存在则根据id查询数据库
//4 不存在,根据id查询数据库
shop = getById(id);
//为了测试,在操作数据库时休眠一段时间,模拟重建的延时
//Thread.sleep(200);
//5 数据库不存在,返回错误
if(shop==null){
//将空值写入Redis
stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL, TimeUnit.MINUTES);
//返回错误信息
return null;
}
//6 数据库存在,将数据写入redis并返回(添加超时时间)
stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL, TimeUnit.MINUTES);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}finally {
//7 释放互斥锁
unlock(lockKey);
}
return shop;
}
}
B.基于逻辑过期实现
1、为了给存入redis的对象增加一个【逻辑过期时间】属性,封装一个RedisData类用于保存要存入redis的热点数据。
@Data
public class RedisData {
private LocalDateTime expireTime;
private Object data;
}
2、基于单元测试将数据加入到缓存中(实际应用中后台会有对应操作的实现)
2.1 封装存储店铺信息和逻辑过期时间的函数
//ShopServiceImpl中封装存储店铺信息和逻辑过期时间的函数
public void saveShop2Redis(Long id,Long expireSeconds){
//1 查询店铺数据
Shop shop = getById(id);
//2 封装逻辑过期时间
RedisData redisData = new RedisData();
redisData.setData(shop);
redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
//3 写入redis(注意这里不添加真正的TTL,而是使用逻辑过期时间来判断)
stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY+id,JSONUtil.toJsonStr(redisData));
}
2.2 测试类中写:
@SpringBootTest
class HmDianPingApplicationTests {
@Resource
private ShopServiceImpl shopService;
@Test
void testSaveShop() {
shopService.saveShop2Redis(1L,10L);
}
}
2.3 实现获取锁及之后的业务逻辑
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
@Resource
private StringRedisTemplate stringRedisTemplate;
/**
* 根据id查询商铺信息
* @param id
* @return
*/
@Override
public Result queryById(Long id) {
//解决缓存穿透
//Shop shop = queryWithPassThrough(id);
//互斥锁解决缓存击穿
//Shop shop = queryWithMutex(id);
//逻辑过期解决缓存击穿
Shop shop = queryWithLogicalExpire(id);
if (shop == null) {
return Result.fail("店铺不存在!");
}
//返回
return Result.ok(shop);
}
//定义线程池
private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);
/**
* 逻辑过期解决缓存击穿
* @param id
* @return
*/
public Shop queryWithLogicalExpire(Long id){
String key = CACHE_SHOP_KEY+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_KEY+id;
boolean isLock = tryLock(lockKey);
//6.2 判断是否成功获取锁
if(isLock){
//TODO: 获取成功,再次检测redis缓存是否存在,如存在则无需创建,不存在则根据id查询数据库
//6.3 成功,开启独立线程实现缓存重建(使用线程池)
CACHE_REBUILD_EXECUTOR.submit(()->{
try {
//重建缓存
this.saveShop2Redis(id,30L);
} catch (Exception e){
throw new RuntimeException(e);
}finally {
//释放锁
unlock(lockKey);
}
});
}
//6.4返回过期的商户信息(无论是否获取锁都要返回)
return shop;
}
//获取锁
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);
}
//存储店铺信息和逻辑过期时间的函数
public void saveShop2Redis(Long id,Long expireSeconds) throws InterruptedException {
//1 查询店铺数据
Shop shop = getById(id);
//为了测试
Thread.sleep(200);
//2 封装逻辑过期时间
RedisData redisData = new RedisData();
redisData.setData(shop);
redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
//3 写入redis(注意这里不添加真正的TTL,而是使用逻辑过期时间来判断)
stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY+id,JSONUtil.toJsonStr(redisData));
}
}
6、缓存工具封装
@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)));
stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
}
//方法三
public <R, ID> R queryWithPassThrough(
String keyPrefix, ID id, Class<R> type, Function<ID, R> 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);
}
// 判断命中的是否为空值,如果不为null则为空字符串""
if (json != null) {
return null;
}
//4 不存在,根据id查询数据库
R r = dbFallback.apply(id);
//5 数据库不存在,返回错误
if (r == null) {
//将空值写入Redis
stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
//返回错误信息
return null;
}
//6 数据库存在,将数据写入redis并返回(添加超时时间)
this.set(key, r, time, unit);
return r;
}
private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);
//方法四
public <R,ID> R queryWithLogicalExpire(
String keyPrefix, ID id, Class<R> type,Function<ID,R> dbFallback, Long time, TimeUnit unit) {
String key = keyPrefix + id;
//1 从redis查询商户缓存
String json = stringRedisTemplate.opsForValue().get(key);
//2 判断是否存在
if (StrUtil.isBlank(json)) {
//3 未命中,直接返回
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 缓存重建
//6.1 获取互斥锁
String lockKey = LOCK_SHOP_KEY + id;
boolean isLock = tryLock(lockKey);
//6.2 判断是否成功获取锁
if (isLock) {
//TODO: 获取成功,再次检测redis缓存是否存在(DoubleCheck),如存在则无需创建,不存在则根据id查询数据库
//6.3 成功,开启独立线程实现缓存重建(使用线程池)
CACHE_REBUILD_EXECUTOR.submit(() -> {
try {
//查询数据库
R r1 = dbFallback.apply(id);
//写入redis
this.setWithLogicalExpire(key,r1,time,unit);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
//释放锁
unlock(lockKey);
}
});
}
//6.4返回过期的商户信息(无论是否获取锁都要返回)
return r;
}
//获取锁
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);
}
}