【从零开始学习Redis】项目实战-黑马点评D2
商户查询缓存
为什么用缓存?
作用模型
缓存流程
按照流程编写代码如下
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {@Resourceprivate StringRedisTemplate stringRedisTemplate;@Overridepublic Result queryById(Long id) {String key = CACHE_SHOP_KEY + id;//从redis查询商铺缓存String shopJson = stringRedisTemplate.opsForValue().get(key);if(StrUtil.isNotBlank(shopJson)){//存在,返回Shop shop = JSONUtil.toBean(shopJson, Shop.class);return Result.ok(shop);}//不存在,查询数据库Shop shop = getById(id);//数据库中不存在,报错if(shop == null){return Result.fail("店铺不存在!");}//存在,写入redisstringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop));//返回return Result.ok(shop);}
}
给shop-type添加Redis缓存
这部分需要自己实现,课程没有答案。
请求URL:[http://localhost:8080/api/shop-type/list](http://localhost:8080/api/shop-type/list)
根据之前给店铺做缓存的思路,这次我们同样使用String类型,用来保存list
类型的店铺类型数据。
代码实现思路仿照给查询店铺缓存的过程。只不过这次是要转为list
类型。
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {@Resourceprivate StringRedisTemplate stringRedisTemplate;@Overridepublic Result queryByType() {String key = "cache:type";// 首先查询redisString shopTypeJson = stringRedisTemplate.opsForValue().get(key);if(StrUtil.isNotBlank(shopTypeJson)){// 如果存在List<ShopType> shopTypes = JSONUtil.toList(shopTypeJson, ShopType.class);return Result.ok(shopTypes);}// 如果不存在,那么查询数据库List<ShopType> shopTypes = query().orderByAsc("sort").list();// 如果数据库中不存在,报错if(shopTypes == null){return Result.fail("无法查询到相关店铺");}// 存在,写入redisstringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shopTypes));return Result.ok(shopTypes);}
}
缓存更新策略
策略选择:
主动更新策略
Cache Aside Pattern
由缓存的调用者,在更新数据库的同时更新缓存
操作缓存和数据库时有三个问题需要考虑:
- 删除缓存还是更新缓存?
- 更新缓存:每次更新数据库都更新缓存,无效写操作较多(F)
- 删除缓存:更新数据库时让缓存失效,查询时再更新缓存(T)
- 如何保证缓存与数据库的操作的同时成功或失败?
- 单体系统,将缓存与数据库操作放在一个事务
- 分布式系统,利用TCC等分布式事务方案
- 先操作缓存还是先操作数据库?
- 先删除缓存,再操作数据库
- 先操作数据库,再删除缓存
对比一下缓存数据库操作顺序的影响(代表异常情况下)
线程一执行删除缓存,这个是快操作,但是更新数据库是慢操作,在二者之间很可能会有线程二,缓存已被删除,查询缓存时未命中,去查数据库写入缓存,这两个都是快操作,数据库和缓存数据不一致,从而导致数据不一致情况。这种情况出现概率较大。
假设刚好线程一进来时缓存失效,那么查询数据库,获得了某个值a
。不巧的是,在线程一写缓存之前,线程二更新了数据库,数据库中变为新的值b
,执行删除缓存(缓存本来就什么也没有),线程一接着写入缓存,可是线程一写入的缓存内容是a
,那么现在数据库的值是b
,缓存中的是a
,导致数据不一致。但是这种情况出现概率较小,因为查询缓存写缓存的速度是很快的,很难有另一个线程穿插在这之间并完成了更新数据库删除缓存。
所以我们一般选择先操作数据库,再操作缓存。
缓存穿透
缓存穿透是指用户请求的数据在缓存和数据库中都不存在,这样缓存永远不会生效,这些请求都会打到数据库。如果发生大量这样的请求,会造成数据库瘫痪。
常见的解决方案有两种:
- 缓存空对象
当用户请求的数据在缓存和数据库都不存在时,我们可以设置当前缓存值为null
。
但是如果无休止的请求不存在的数据,就会导致缓存值越来越多,内存消耗越来越大。所以需要设置过期时间TTL
。
同时缓存设置为null
了,如果下次更新数据在数据库中更新了,此时就会导致数据不一致。可以把过期时间设置的短一些,缓解此问题。
- 优点:实现简单,维护方便
- 缺点:
- 额外的内存消耗
- 可能造成短期的不一致
- 布隆过滤器
- 优点:内存占用较少, 没有多余key
- 缺点:
- 实现复杂
- 存在误判可能
- 增强id的复杂度,避免被猜测id规律
- 做好数据的基础格式校验
- 加强用户权限校验
- 做好热点参数的限流
为解决穿透问题我们需要修改业务代码,这里采用缓存null
值方法
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {@Resourceprivate StringRedisTemplate stringRedisTemplate;@Overridepublic Result queryById(Long id) {String key = CACHE_SHOP_KEY + id;//从redis查询商铺缓存String shopJson = stringRedisTemplate.opsForValue().get(key);if(StrUtil.isNotBlank(shopJson)){//存在,返回Shop shop = JSONUtil.toBean(shopJson, Shop.class);return Result.ok(shop);}//判断命中的是否是空值if(shopJson != null){// 返回一个错误信息return Result.fail("店铺信息不存在!");}//不存在,查询数据库Shop shop = getById(id);//数据库中不存在,报错if(shop == null){//将空值写入redisstringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);return Result.fail("店铺不存在!");}//存在,写入redisstringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);//返回return Result.ok(shop);}@Override@Transactionalpublic Result update(Shop shop) {Long id = shop.getId();if(id == null){return Result.fail("商铺id不能为空");}//先更新数据库updateById(shop);//再删缓存stringRedisTemplate.delete(CACHE_SHOP_KEY + shop.getId());return Result.ok(shop);}
}
缓存雪崩
缓存雪崩是指在同一时段大量的缓存key同时失效或者Redis服务宕机,导致大量请求到达数据库,带来巨大压力。
解决方案:
- 给不同的Key的TTL添加随机值
- 利用Redis集群提高服务的可用性
- 给缓存业务添加降级限流策略
- 给业务添加多级缓存
缓存击穿
缓存击穿问题也叫热点Key问题,就是一个被高并发访问并且缓存重建业务较复杂的key突然失效了,无数的请求访问会在瞬间给数据库带来巨大的冲击。
常见的解决方案有两种:
- 互斥锁
- 逻辑过期
解决方案 | 优点 | 缺点 |
---|---|---|
互斥锁 | 没有额外的内存消耗 保证一致性 实现简单 | 线程需要等待, 性能受影响 可能有死锁风险 |
逻辑过期 | 线程无需等待, 性能较好 | 不保证一致性 有额外内存消耗 实现复杂 |
利用互斥锁解决缓存击穿问题
修改根据id查询商铺的业务
这里我们使用Redis中String的setnx模拟上锁,setnx仅当值为空时才可以修改值,这可以模拟互斥锁,当大量请求到当前缓存时,只有一个请求能进一步的进行查数据库、写入Redis、释放锁等功能。这样其他线程就会休眠直到当前线程释放锁。
public Shop queryWithMutex(Long id){
String key = CACHE_SHOP_KEY + id;
//从redis查询商铺缓存
String shopJson = stringRedisTemplate.opsForValue().get(key);
if(StrUtil.isNotBlank(shopJson)){//存在,返回return JSONUtil.toBean(shopJson, Shop.class);
}
//判断命中的是否是空值
if(shopJson != null){// 返回一个错误信息return null;
}
// 实现缓存重建
// 获取互斥锁
String lockKey = LOCK_SHOP_KEY + id;
Shop shop = null;
try {boolean isLock = tryLock(lockKey);// 判断是否获取成功if(!isLock){// 失败则休眠重试Thread.sleep(50);return queryWithMutex(id);}// 成功,根据id查询数据库shop = getById(id);// 模拟重建延时Thread.sleep(200);//数据库中不存在,报错if(shop == null){//将空值写入redisstringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);return null;}//存在,写入redisstringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);} catch (InterruptedException e) {throw new RuntimeException(e);
} finally {// 释放互斥锁unlock(lockKey);}
//返回
return shop;
}private boolean tryLock(String key){Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);return BooleanUtil.isTrue(flag); //不直接return flag,因为在拆箱过程中可能产生空指针
}private void unlock(String key){
stringRedisTemplate.delete(key);
}
利用逻辑过期解决缓存击穿问题
重建缓存的方法
private 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.写入redisstringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));
}
业务逻辑实现
这里使用了线程池,避免了线程频繁的创建销毁带来的性能开销。
private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);public Shop queryWithLogicalExpire(Long id) {
String key = CACHE_SHOP_KEY + id;
//从redis查询商铺缓存
String shopJson = stringRedisTemplate.opsForValue().get(key);
if (StrUtil.isBlank(shopJson)) {//不存在,返回return null;
}
// 命中,把Json反序列化为对象
RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
Shop shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
LocalDateTime expireTime = redisData.getExpireTime();
// 判断是否过期
if(expireTime.isAfter(LocalDateTime.now())){// 未过期,返回商铺信息return shop;
}
// 已过期,需要缓存重建
// 缓存重建
// 获取互斥锁
String lockKey = LOCK_SHOP_KEY + id;
boolean isLock = tryLock(lockKey);
// 判断是否获取成功
if(isLock){//成功则开启独立线程,缓存重建CACHE_REBUILD_EXECUTOR.submit(()->{try {//重建缓存this.saveShop2Redis(id, 20L);} catch (Exception e) {throw new RuntimeException(e);} finally {//释放锁unlock(lockKey);}});
}//失败则返回过期的商户信息
return shop;
}
封装缓存工具类
封装Redis工具类
基于StringRedisTemplate封装一个缓存工具类,满足下列需求:
- 方法1:将任意Java对象序列化为json并存储在string类型的key中,并且可以设置TTL过期时间
- 方法2:将任意Java对象序列化为json并存储在string类型的key中,并且可以设置逻辑过期时间,用于处理缓
存击穿问题
- 方法3:根据指定的key查询缓存,并反序列化为指定类型,利用缓存空值的方式解决缓存穿透问题
- 方法4:根据指定的key查询缓存,并反序列化为指定类型,需要利用逻辑过期解决缓存击穿问题
将逻辑进行封装
@Slf4j
@Component
public class CacheClient {private final 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.setData(value);redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));// 写入RedisstringRedisTemplate.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);}// 判断命中的是否是空值if (json != null) {// 返回一个错误信息return null;}// 4.不存在,根据id查询数据库R r = dbFallback.apply(id);// 5.不存在,返回错误if (r == null) {// 将空值写入redisstringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);// 返回错误信息return null;}// 6.存在,写入redisthis.set(key, r, time, unit);return r;}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){// 6.3.成功,开启独立线程,实现缓存重建CACHE_REBUILD_EXECUTOR.submit(() -> {try {// 查询数据库R newR = dbFallback.apply(id);// 重建缓存this.setWithLogicalExpire(key, newR, time, unit);} catch (Exception e) {throw new RuntimeException(e);}finally {// 释放锁unlock(lockKey);}});}// 6.4.返回过期的商铺信息return r;}public <R, ID> R queryWithMutex(String keyPrefix, ID id, Class<R> type, Function<ID, R> dbFallback, Long time, TimeUnit unit) {String key = keyPrefix + id;// 1.从redis查询商铺缓存String shopJson = stringRedisTemplate.opsForValue().get(key);// 2.判断是否存在if (StrUtil.isNotBlank(shopJson)) {// 3.存在,直接返回return JSONUtil.toBean(shopJson, type);}// 判断命中的是否是空值if (shopJson != null) {// 返回一个错误信息return null;}// 4.实现缓存重建// 4.1.获取互斥锁String lockKey = LOCK_SHOP_KEY + id;R r = null;try {boolean isLock = tryLock(lockKey);// 4.2.判断是否获取成功if (!isLock) {// 4.3.获取锁失败,休眠并重试Thread.sleep(50);return queryWithMutex(keyPrefix, id, type, dbFallback, time, unit);}// 4.4.获取锁成功,根据id查询数据库r = dbFallback.apply(id);// 5.不存在,返回错误if (r == null) {// 将空值写入redisstringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);// 返回错误信息return null;}// 6.存在,写入redisthis.set(key, r, time, unit);} catch (InterruptedException e) {throw new RuntimeException(e);}finally {// 7.释放锁unlock(lockKey);}// 8.返回return r;}private boolean tryLock(String key) {Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);return BooleanUtil.isTrue(flag);}private void unlock(String key) {stringRedisTemplate.delete(key);}
}
在shopServiceImpl中
@Resource
private CacheClient cacheClient;@Overridepublic Result queryById(Long id) {// 解决缓存穿透Shop shop = cacheClient.queryWithPassThrough(CACHE_SHOP_KEY, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);// 互斥锁解决缓存击穿// Shop shop = cacheClient// .queryWithMutex(CACHE_SHOP_KEY, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);// 逻辑过期解决缓存击穿// Shop shop = cacheClient// .queryWithLogicalExpire(CACHE_SHOP_KEY, id, Shop.class, this::getById, 20L, TimeUnit.SECONDS);if (shop == null) {return Result.fail("店铺不存在!");}// 7.返回return Result.ok(shop);}
如果内容对你有所帮助,请点赞、评论、收藏,创作不易,你的支持是我创作的动力。