商户查询缓存

HeJin大约 11 分钟项目实战Redis项目实战

01.什么是缓存

缓存就是数据交换的缓冲区(称作Cache),是存贮数据的临时地方,一般读写性能较高。

  • 浏览器缓存。
  • 应用层缓存。
  • 数据库缓存。
  • CPU缓存。
  • 磁盘缓存。

缓存的作用

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

缓存的成本

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

02.添加商户缓存

缓存作用模型

image-20230129131633021
image-20230129131633021

根据id查询商铺缓存的流程

image-20230129133922464
image-20230129133922464

添加商铺查询缓存

ShopServiceImpl:Redis的value使用String。

@Override
public Result queryShopById(Long id) {
    Shop shop;
    // 1.Redis查询商铺缓存
    String shopKey = RedisConstants.CACHE_SHOP_KEY + id;
    String shopJson = stringRedisTemplate.opsForValue().get(shopKey);
    if (ObjectUtil.isNotEmpty(shopJson)){
        shop = JSONUtil.toBean(shopJson, Shop.class);
        return Result.ok(shop);
    }
    // 2.缓存未命中: 查询数据库
    shop = getById(id);
    if (ObjectUtil.isEmpty(shop)){
        return Result.fail("店铺不存在!");
    }
    // 3.商铺数据写入Redis
    stringRedisTemplate.opsForValue().set(shopKey, JSONUtil.toJsonStr(shop));
    // 4.返回商铺信息
    return Result.ok(shop);
}

添加店铺类型查询缓存

ShopTypeServiceImpl:Redis的value使用Set。

@Override
public Result queryTypeList() {
    Set<ShopType> shopTypeSet;
    // 1.Redis查询店铺类型
    String shopTypeKey = RedisConstants.CACHE_SHOP_TYPE_KEY;
    Set<String> shopTypeJson = stringRedisTemplate.opsForSet().members(shopTypeKey);
    if (Objects.nonNull(shopTypeJson) && !shopTypeJson.isEmpty()){
        shopTypeSet = shopTypeJson.stream()
                .map(st -> JSONUtil.toBean(st, ShopType.class))
                .collect(Collectors.toSet());
        return Result.ok(shopTypeSet);
    }
    // 2.缓存未命中,查询数据库
    List<ShopType> shopTypes = query().orderByAsc("sort").list();
    shopTypeSet = new HashSet<>(shopTypes);
    if (ObjectUtil.isEmpty(shopTypeSet) || shopTypeSet.isEmpty()){
        return Result.fail("店铺类型无数据");
    }
    // 3.店铺类型数据写入缓存
    for (ShopType shopType : shopTypeSet) {
        stringRedisTemplate.opsForSet().add(shopTypeKey, JSONUtil.toJsonStr(shopType));
    }
    // 4.返回店铺类型数据
    return Result.ok(shopTypeSet);
}

03.缓存更新策略

策略选择

内存淘汰超时剔除主动更新
说明不用自己维护,利用Redis的内存淘汰机制。当内存不足时,自动淘汰部分数据,下次查询时更新缓存。给缓存数据添加TTL时间,到期后自动删除缓存,下次查询时更新缓存。编写业务逻辑,在修改数据库的同时,更新缓存。
一致性一般
维护成本

业务场景:

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

主动更新

  • Cache Aside Pattern:由缓存的调用者,在更新数据库的同时更新缓存。
  • Read/Write Through Pattern:缓存与数据库整合为一个服务,由服务来维护一致性。调用者调用该服务,无需关心缓存一致性问题。
  • Write Behind Caching Pattern:调用者只操作缓存,由其它线程异步的将缓存数据持久化到数据库,保证最终一致。

最后选择的是Cache Aside Pattern,因为这可以保持数据库和缓存的数据一致性。

主动更新策略Cache Aside Pattern,操作缓存和数据库时有三个问题需要考虑:

  • 删除缓存还是更新缓存?

    • 更新缓存:每次更新数据库都更新缓存,无效写操作较多。
    • 删除缓存:更新数据库时让缓存失效,查询时再更新缓存。
  • 如何保证缓存与数据库的操作的同时成功或失败?

    • 单体系统,将缓存与数据库操作放在一个事务。
    • 分布式系统,利用TCC等分布式事务方案。
  • 先操作缓存还是先操作数据库?

    • 先删除缓存,再操作数据库。
    • 先操作数据库,再删除缓存。

最佳实践

  • 低一致性需求:使用Redis自带的内存淘汰机制。
  • 高一致性需求:主动更新,并以超时剔除作为兜底方案。
    • 读操作:缓存命中则直接返回。缓存未命中则查询数据库,并写入缓存,设定超时时间。
    • 写操作:先写数据库,然后再删除缓存。要确保数据库与缓存操作的原子性。

04.商铺缓存和数据库的双写一致

商铺存入redis添加过期时间:

ShopServiceImpl

@Override
public Result queryShopById(Long id) {
    Shop shop;
    // 1.Redis查询商铺缓存
    String shopKey = RedisConstants.CACHE_SHOP_KEY + id;
    String shopJson = stringRedisTemplate.opsForValue().get(shopKey);
    if (ObjectUtil.isNotEmpty(shopJson)){
        shop = JSONUtil.toBean(shopJson, Shop.class);
        return Result.ok(shop);
    }
    // 2.缓存未命中: 查询数据库
    shop = getById(id);
    if (ObjectUtil.isEmpty(shop)){
        return Result.fail("店铺不存在!");
    }
    // 3.商铺数据写入Redis: 添加过期时间
    stringRedisTemplate.opsForValue().set(shopKey, JSONUtil.toJsonStr(shop), RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
    // 4.返回商铺信息
    return Result.ok(shop);
}

ShopController

@PutMapping
public Result updateShop(@RequestBody Shop shop) {
    if (null == shop.getId()){
        return Result.fail("店铺id不能为空!");
    }
    return shopService.updateShop(shop);
}

ShopServiceImpl

@Override
@Transactional(rollbackFor = Exception.class)
public Result updateShop(Shop shop) {
    // 1.更新数据库
    updateById(shop);
    // 2.删除缓存
    stringRedisTemplate.delete(RedisConstants.CACHE_SHOP_KEY + shop.getId());

    return Result.ok();
}

05.缓存穿透问题及解决思路

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

常见的解决方案有两种:

  • 缓存空对象:
    • 优点:实现简单,维护方便。
    • 缺点:额外的内存消耗,可能造成短期的不一致。
  • 布隆过滤:
    • 优点:内存占用较少,没有多余key。
    • 缺点:实现复杂,存在误判可能。
image-20230129145153330
image-20230129145153330

缓存穿透产生的原因是什么?

用户请求的数据在缓存中和数据库中都不存在,不断发起这样的请求,给数据库带来巨大压力

缓存穿透的解决方案有哪些?

  • 缓存null值。
  • 布隆过滤。
  • 增强id的复杂度,避免被猜测id规律。
  • 做好数据的基础格式校验。
  • 加强用户权限校验。
  • 做好热点参数的限流。

06.解决商铺查询缓存穿透

image-20230129170050601
image-20230129170050601

ShopServiceImpl:缓存穿透解决方案是缓存null值。

@Override
public Result queryShopById(Long id) {
    Shop shop;
    // 1.Redis查询商铺缓存
    String shopKey = RedisConstants.CACHE_SHOP_KEY + id;
    String shopJson = stringRedisTemplate.opsForValue().get(shopKey);
    if (StrUtil.isNotBlank(shopJson)){
        shop = JSONUtil.toBean(shopJson, Shop.class);
        return Result.ok(shop);
    }
    // 命中是否为空值
    if (Objects.nonNull(shopJson)){
        return Result.fail("店铺不存在!");
    }
    // 2.缓存未命中: 查询数据库
    shop = getById(id);
    if (ObjectUtil.isEmpty(shop)){
        // 将空值写入Redis
        stringRedisTemplate.opsForValue().set(shopKey, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
        return Result.fail("店铺不存在!");
    }
    // 3.商铺数据写入Redis
    stringRedisTemplate.opsForValue().set(shopKey, JSONUtil.toJsonStr(shop), RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
    // 4.返回商铺信息
    return Result.ok(shop);
}

07.缓存雪崩问题及解决思路

缓存雪崩是指在同一时段大量的缓存key同时失效或者Redis服务宕机,导致大量请求到达数据库,带来巨大压力。

解决方案

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

08.缓存击穿问题及解决思路

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

image-20230131113128629
image-20230131113128629

常见的解决方案有两种:

  • 互斥锁。

    image-20230131115725079
    image-20230131115725079
  • 逻辑过期。

    image-20230131115944992
    image-20230131115944992
解决方案优点缺点
互斥锁没有额外的内存消耗
保证一致性
实现简单
线程需要等待,性能受影响
可能有死锁风险
逻辑过期线程无需等待,性能较好不保证一致性
有额外内存消耗
实现复杂

09.利用互斥锁解决缓存击穿问题

互斥锁解决商铺查询

image-20230131121810314
image-20230131121810314

ShopServiceImpl

@Override
public Result queryShopById(Long id) {
    Shop shop = queryWithMutex(id);
    if (Objects.isNull(shop)){
        return Result.fail("店铺不存在");
    }
    return Result.ok(shop);
}

/**
 * 解决商铺查询缓存击穿: 互斥锁
 * @param id 商铺id
 * @return 商铺信息
 */
private Shop queryWithMutex(Long id) {
    Shop shop = null;
    // 1.Redis查询商铺缓存
    String shopKey = RedisConstants.CACHE_SHOP_KEY + id;
    String shopJson = stringRedisTemplate.opsForValue().get(shopKey);
    if (StrUtil.isNotBlank(shopJson)){
        shop = JSONUtil.toBean(shopJson, Shop.class);
        return shop;
    }
    // 命中是否为空值
    if (RedisConstants.CACHE_NULL_VALUE.equals(shopJson)){
        return null;
    }
    // 2.实现缓存重建
    // 2.1 获取互斥锁
    String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
    try {
        boolean isLock = tryLock(lockKey);
        // 2.2判断是否获取成功
        if (!isLock){
            // 2.3 获取锁失败,休眠并重试
            Thread.sleep(50);
            return queryWithMutex(id);
        }
        // 2.4.1 获取锁成功,查询缓存
        shopJson = stringRedisTemplate.opsForValue().get(shopKey);
        if (StrUtil.isNotBlank(shopJson)){
            shop = JSONUtil.toBean(shopJson, Shop.class);
            return shop;
        }
        // 命中是否为空值
        if (RedisConstants.CACHE_NULL_VALUE.equals(shopJson)){
            return null;
        }
        // 2.4.2 获取锁成功,查询数据库
        shop = getById(id);
        // 模拟重建的延时
        Thread.sleep(200);
        if (ObjectUtil.isEmpty(shop)){
            // 将空值写入Redis
            stringRedisTemplate.opsForValue().set(shopKey, RedisConstants.CACHE_NULL_VALUE, RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        // 3.商铺数据写入Redis
        stringRedisTemplate.opsForValue().set(shopKey, JSONUtil.toJsonStr(shop), RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
    } catch (InterruptedException e) {
        throw new RuntimeException();
    } finally {
        // 4.释放互斥锁
        unlock(lockKey);
    }
    // 5.返回商铺信息
    return shop;
}

互斥锁的获取和释放

/**
 * 获取互斥锁
 * @param key key
 * @return boolean
 */
private boolean tryLock(String key){
    Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", RedisConstants.LOCK_SHOP_TTL, TimeUnit.SECONDS);
    return BooleanUtil.isTrue(flag);
}

/**
 * 释放互斥锁
 * @param key key
 */
private void unlock(String key){
    stringRedisTemplate.delete(key);
}

10.利用逻辑过期解决缓存击穿问题

需求:修改根据id查询商铺的业务,基于逻辑过期方式来解决缓存击穿问题。

image-20230131123513626
image-20230131123513626
private static final ExecutorService CACHE_REBUILD_EXECUTOR = new ThreadPoolExecutor(
        10,
        15,
        20, TimeUnit.SECONDS,
        new LinkedBlockingQueue<>(),
        ThreadFactoryBuilder.create().build(),
        new ThreadPoolExecutor.AbortPolicy());

private Shop queryWithLogicExpire(Long id) {
    // 1.Redis查询商铺缓存
    String shopKey = RedisConstants.CACHE_SHOP_KEY + id;
    String shopJson = stringRedisTemplate.opsForValue().get(shopKey);
    // 1.1 缓存未命中
    if (StrUtil.isBlank(shopJson)){
        // 直接返回null
        return null;
    }
    // 2.命中: json反序列化
    RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
    Shop shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
    LocalDateTime expireTime = redisData.getExpireTime();
    // 3.判断是否过期
    if (expireTime.isAfter(LocalDateTime.now())){
        // 3.1 未过期,直接返回店铺信息
        return shop;
    }
    // 3.2 已过期,需要缓存重建
    // 4.缓存重建
    // 4.1 获取互斥锁
    String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
    boolean isLock = tryLock(lockKey);
    // 4.2 判断是否获取锁成功
    if (isLock){
        // 4.3 成功,开启独立线程,实现缓存重建
        // 4.3.1 再次查询缓存,命中直接返回
        shopJson = stringRedisTemplate.opsForValue().get(shopKey);
        if (StrUtil.isNotBlank(shopJson)){
            redisData = JSONUtil.toBean(shopJson, RedisData.class);
            shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
            expireTime = redisData.getExpireTime();
            // 3.判断是否过期
            if (expireTime.isAfter(LocalDateTime.now())){
                // 3.1 未过期,直接返回店铺信息
                return shop;
            }
        }
        // 4.3.2 未命中,缓存重建
        CACHE_REBUILD_EXECUTOR.submit(() -> {
            try {
                this.saveShop2Redis(id, 20L);
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                // 释放锁
                unlock(lockKey);
            }
        });
    }
    return shop;
}

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));
    // 存入Redis
    stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));
}

11.封装Redis工具类

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

  • 方法1:将任意Java对象序列化为json并存储在string类型的key中,并且可以设置TTL过期时间。

    /**
     * 往Redis存储数据,并设置过期时间
     * @param key 存储key
     * @param object 存储value
     * @param time 过期时间
     * @param unit 时间单位
     */
    public void set(String key, Object object, Long time, TimeUnit unit){
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(object), time, unit);
    }
    
  • 方法2:将任意Java对象序列化为json并存储在string类型的key中,并且可以设置逻辑过期时间,用于处理缓存击穿问题。

    /**
     * 往Redis存储数据,并设置逻辑过期
     * @param key 存储key
     * @param object 存储value
     * @param time 逻辑过期时间
     * @param unit 时间单位
     */
    public void setWithLogicExpire(String key, Object object, Long time, TimeUnit unit){
        RedisData redisData = new RedisData();
        redisData.setData(object);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }
    
  • 方法3:根据指定的key查询缓存,并反序列化为指定类型,利用缓存空值的方式解决缓存穿透问题。

    /**
     * 解决查询缓存穿透: 缓存null值
     * @param keyPrefix key前缀
     * @param id 对象id
     * @param type 对象Class
     * @param dbFallback 数据库查询语句
     * @param time 过期时间
     * @param unit 时间单位
     * @param <R> 返回类型
     * @param <T> id类型
     * @return R
     */
    public <R, T> R queryWithPassThrough(String keyPrefix, T id, Class<R> type,
                                          Function<T, 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 (Objects.nonNull(json)){
            return null;
        }
        R r = dbFallback.apply(id);
        if (ObjectUtil.isEmpty(r)){
            this.set(key, RedisConstants.CACHE_NULL_VALUE, RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        this.set(key, r, time, unit);
        return r;
    }
    
  • 方法4:根据指定的key查询缓存,并反序列化为指定类型,需要利用逻辑过期解决缓存击穿问题。

    /**
     * 逻辑过期解决缓存穿透查询
     * @param keyPrefix key前缀
     * @param id 对象id
     * @param type 对象类型
     * @param dbFallback 数据查询语句
     * @param time 逻辑过期时间
     * @param unit 时间单位
     * @param <R> 返回类型
     * @param <T> id类型
     * @return R
     */
    public <R, T> R queryWithLogicExpire(String keyPrefix, T id, Class<R> type,
                                          Function<T, R> dbFallback, Long time, TimeUnit unit) {
        String key = keyPrefix + 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 = RedisConstants.LOCK_SHOP_KEY + id;
        boolean isLock = tryLock(lockKey);
        if (isLock){
            // 获取锁之后再次查询缓存
            json = stringRedisTemplate.opsForValue().get(key);
            if (StrUtil.isNotBlank(json)){
                redisData = JSONUtil.toBean(json, RedisData.class);
                r = JSONUtil.toBean((JSONObject) redisData.getData(), type);
                expireTime = redisData.getExpireTime();
                if (expireTime.isAfter(LocalDateTime.now())){
                    return r;
                }
            }
            // 缓存重建
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    R r1 = dbFallback.apply(id);
                    this.setWithLogicExpire(key, r1, time, unit);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    unlock(lockKey);
                }
            });
        }
        return r;
    }
    

完整代码:CacheClientopen in new window