当前位置: 首页 > news >正文

Redis--day6--黑马点评--商户查询缓存

请添加图片描述
(以下内容全部来自上述课程)
在这里插入图片描述

商户查询缓存

1. 什么是缓存

缓存就是数据交换的缓冲区,是存储数据的临时地方,一般读写性能较高。
请添加图片描述
缓存的作用:

  • 降低后端负载
  • 提高读写效率
  • 降低响应时间

缓存的成本:

  • 数据一致性成本
  • 代码维护成本
  • 运维成本

2. 添加商户缓存

请添加图片描述
shopServiceImpl.java:

package com.hmdp.service.impl;import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.hmdp.utils.CacheClient;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;import static com.hmdp.utils.RedisConstants.CACHE_SHOP_KEY;
import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TTL;/*** <p>*  服务实现类* </p>** @author 虎哥* @since 2021-12-22*/
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {@Resourceprivate StringRedisTemplate stringRedisTemplate;@Overridepublic Result queryById(Long id) {String key = "cache:shop:"+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. 存在,写入redisstringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shopJson));//7. 返回return Result.ok(shop);}
}

3. 缓存更新策略

请添加图片描述
业务场景:

  • 低一致性需求:使用内存淘汰机制。例如店铺类型的查询缓存。
  • 高一致性需求:主动更新,并以超时剔除作为兜底方案。例如店铺详情查询的缓存。

3.1 主动更新策略

请添加图片描述
方案一最常用。

3.2 Cache Aside Pattern

操作缓存和数据库时有三个问题需要考虑:

  1. 删除缓存还是更新缓存?
  • 更新缓存:每次更新数据库都更新缓存,无效写操作较多 ×
  • 删除缓存:更新数据库时让缓存失效,查询时再更新缓存 √
  1. 如何保证缓存与数据库的操作的同时成功或失败?
  • 单体系统,将缓存与数据库操作放在一个事务
  • 分布式系统,利用TCC等分布式事务方案
  1. 先操作缓存还是先操作数据库?
  • 先删除缓存,再操作数据库
  • 先操作数据库,再删除缓存
    请添加图片描述

4. 实现商铺缓存与数据库的双写一致

修改ShopController中的业务逻辑,满足下面的需求

  1. 根据id查询店铺时,如果缓存未命中,则查询数据库,将数据库结果写入缓存,并设置超时时间
  2. 根据id修改店铺时先修改数据库,再删除缓存

目前全部代码:ShopServiceImpl.java:

package com.hmdp.service.impl;import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.hmdp.utils.CacheClient;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;import static com.hmdp.utils.RedisConstants.CACHE_SHOP_KEY;
import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TTL;/*** <p>*  服务实现类* </p>** @author 虎哥* @since 2021-12-22*/
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {@Resourceprivate StringRedisTemplate stringRedisTemplate;@Overridepublic Result queryById(Long id) {String key = "cache:shop:"+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. 存在,写入redisstringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL,TimeUnit.MINUTES);//7. 返回return Result.ok(shop);}
}

更改部分:ShopController.java——>

 /*** 更新商铺信息* @param shop 商铺数据* @return 无*/@PutMappingpublic Result updateShop(@RequestBody Shop shop) {// 写入数据库return shopService.update(shop);}

目前全部代码:IShopService——>

package com.hmdp.service;import com.baomidou.mybatisplus.extension.service.IService;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;/*** <p>*  服务类* </p>** @author 虎哥* @since 2021-12-22*/
public interface IShopService extends IService<Shop>{Result queryById(Long id);Result update(Shop shop);
}

更改部分:ShopServiceImpl.java:

@Override@Transactionalpublic Result update(Shop shop) {if (shop.getId() == null) {return Result.fail("店铺id不能为空");}//1. 更新数据库updateById(shop);//2. 删除缓存stringRedisTemplate.delete(CACHE_SHOP_KEY+shop.getId());return Result.ok();}

5. 缓存穿透

缓存穿透是指客户端请求的数据在缓存中和数据库中都不存在,这样缓存永远不会生效,这些请求都会打到数据库。

常见的解决方法有两种:

  • 缓存空对象
    优点:实现简单,维护方便
    缺点:额外的内存消耗,可能造成短期的不一致
    请添加图片描述

  • 布隆过滤
    优点:内存占用较少,没有多余key
    缺点:实现复杂,存在误判可能
    请添加图片描述

6. 编码解决商铺查询的缓存穿透问题(NULL)

请添加图片描述
当前所有代码:ShopServiceImpl.java:

package com.hmdp.service.impl;import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.hmdp.utils.CacheClient;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;import static com.hmdp.utils.RedisConstants.*;/*** <p>*  服务实现类* </p>** @author 虎哥* @since 2021-12-22*/
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {@Resourceprivate StringRedisTemplate stringRedisTemplate;@Overridepublic Result queryById(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 Result.ok(shop);}//判断命中的是否是空值if(shopJson != null){//返回一个错误信息return Result.fail("店铺不存在!");}//4. 不存在,根据id查询数据库Shop shop = getById(id);//5. 不存在,返回错误if (shop == null) {//将空值写入redisstringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL,TimeUnit.MINUTES);return  Result.fail("商户不存在");}//6. 存在,写入redisstringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL,TimeUnit.MINUTES);//7. 返回return Result.ok(shop);}@Override@Transactionalpublic Result update(Shop shop) {if (shop.getId() == null) {return Result.fail("店铺id不能为空");}//1. 更新数据库updateById(shop);//2. 删除缓存stringRedisTemplate.delete(CACHE_SHOP_KEY+shop.getId());return Result.ok();}
}

7. 缓存雪崩

缓存雪崩是指在同一时段大量的缓存key同时失效或者Redis服务宕机,导致大量请求到达数据库,带来巨大压力。
请添加图片描述
解决方案:

  • 给不同的Key的TTL添加随机值
  • 利用Redis集群提高服务的可能性
  • 给缓存业务添加降级限流策略
  • 给业务添加多级缓存

8. 缓存击穿

缓存击穿问题也叫热点Key问题,就是一个被高并发访问并且缓存重构业务较复杂的key突然失效了,无数的请求访问会在瞬间给数据库带来巨大的冲击。
请添加图片描述
解决方案:

  • 互斥锁
    请添加图片描述

  • 逻辑过期
    请添加图片描述
    请添加图片描述

9. 基于互斥锁方式解决缓存击穿问题

需求:修改根据id查询商铺的业务,基于互斥锁方式来解决缓存击穿问题。
请添加图片描述
目前所有代码:shopServiceImpl.java:

package com.hmdp.service.impl;import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.hmdp.utils.CacheClient;
import lombok.val;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;import static com.hmdp.utils.RedisConstants.*;/*** <p>*  服务实现类* </p>** @author 虎哥* @since 2021-12-22*/
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {@Resourceprivate StringRedisTemplate stringRedisTemplate;@Overridepublic Result queryById(Long id) throws InterruptedException {//缓存穿透//Shop shop = queryWithPassThrough(id);//互斥锁解决缓存击穿Shop shop = queryWithMutex(id);if(shop == null){return Result.fail("店铺不存在!");}//7. 返回return Result.ok(shop);}public Shop queryWithMutex(Long id) throws InterruptedException {String key = CACHE_SHOP_KEY + id;//1. 从redis查询商户缓存String shopJson = stringRedisTemplate.opsForValue().get(key);//2. 判断是否存在if (StrUtil.isNotBlank(shopJson)) {//3. 存在,直接返回return JSONUtil.toBean(shopJson, Shop.class);}//判断命中的是否是空值if (shopJson != null) {//返回一个错误信息return null;}//4. 实现缓存重建//4.1 获取互斥锁String lockKey = "lock:shop:" + id;Shop shop;try {boolean isLock = tryLock(lockKey);//4.2 判断是否获取成功if (!isLock) {//4.3 失败,休眠并重眠Thread.sleep(50);queryWithMutex(id);}//4.4 成功,根据id查询数据库shop = getById(id);//5. 不存在,返回错误if (shop == null) {//将空值写入redisstringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);return null;}//6. 存在,写入redisstringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);} catch (InterruptedException e) {throw new RuntimeException(e);} finally {//7. 释放互斥锁unlock(lockKey);}//8. 返回return shop;}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);}@Override@Transactionalpublic Result update(Shop shop) {if (shop.getId() == null) {return Result.fail("店铺id不能为空");}//1. 更新数据库updateById(shop);//2. 删除缓存stringRedisTemplate.delete(CACHE_SHOP_KEY+shop.getId());return Result.ok();}
}

10. 基于逻辑过期方式解决缓存击穿问题

需求:修改根据id查询商铺的业务,基于逻辑过期方式来解决缓存击穿问题。
请添加图片描述
额外添加:RedisData.java:

package com.hmdp.utils;import lombok.Data;import java.time.LocalDateTime;@Data
public class RedisData {private LocalDateTime expireTime;private Object data;
}

新添加的代码:ShopServiceImpl.java:

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));}

新添加的代码:ShopServiceImpl.java:

private static final ExecutorService CACGE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);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) {//6.3 成功,开启独立线程,实现缓存重建CACGE_REBUILD_EXECUTOR.submit(() -> {try {//重建this.saveShop2Redis(id, 30L);}catch (Exception e){throw new RuntimeException(e);}finally {//释放锁unlock(lockKey);}});}//6.4 失败,返回过期的商铺信息return shop;}

11. 封装Redis工具类

基于StringRedisTemplate封装一个缓存工具类,满足下列需求:

  • 方法1:将任意Java对象序列化为json并存储在string类型的key中,并且可以设置TTL过期时间
  • 方法2:将任意lava对象序列化为ison并存储在string类型的key中,并且可以设置逻辑过期时间,用于处理缓存击穿问题
  • 方法3:根据指定的key查询缓存,并反序列化为指定类型,利用缓存空值的方式解决缓存穿透问题
  • 方法4:根据指定的key查询缓存,并反序列化为指定类型,需要利用逻辑过期解决缓存击穿问题
package com.hmdp.utils;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;import static com.hmdp.utils.RedisConstants.CACHE_NULL_TTL;
import static com.hmdp.utils.RedisConstants.LOCK_SHOP_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);}
}
http://www.dtcms.com/a/334481.html

相关文章:

  • 极简工具箱:安卓工具箱合集
  • redis的key过期删除策略和内存淘汰机制
  • Python爬虫实战:研究pygalmesh,构建Thingiverse平台三维网格数据处理系统
  • 记录Linux的指令学习
  • ktg-mes 改造成 Saas 系统
  • 后量子密码算法ML-DSA介绍及开源代码实现
  • 343整数拆分
  • 实例分割-动手学计算机视觉13
  • MQ积压如何处理
  • ABAP AMDP 是一项什么技术?
  • 深入理解Java虚拟机(JVM):架构、内存管理与性能调优
  • MongoDB 聚合提速 3 招:$lookup 管道、部分索引、时间序列集合(含可复现实验与 explain 统计)
  • 片料矫平机·第四篇
  • Element Plus 中 el-input 限制为数值输入的方法
  • 暴雨服务器:以定制化满足算力需求多样化
  • 深入剖析跳表:高效搜索的动态数据结构
  • 【测试工具】OnDo SIP Server--轻松搭建一个语音通话服务器
  • 社保、医保、个税、公积金纵向横向合并 python3
  • 深入理解 Vue Router
  • Centos7.9安装Dante
  • 04时间复杂度计算方法
  • Python 桌面应用形态后台管理系统的技术选型与方案报告
  • Linux系统之lslogins 命令详解
  • vector 手动实现 及遇到的各种细节问题
  • 深入剖析 TOTP 算法:基于时间的一次性密码生成机制
  • Golang分布式事务处理方案
  • 如何在win服务器中部署若依项目
  • JVM垃圾回收器
  • 深度解析Java synchronized关键字及其底层实现原理
  • python学习DAY43打卡