Skip to content
DAILY QUOTE

“ ”

需求:修改ShopController,给查询商铺的缓存添加超时剔除和主动更新的策略

  • 根据id查询店铺时,如果缓存未命中,则查询数据库,将数据库结果写入缓存,并设置超时时间。
java
/**
 * 根据id查询数据。
 *
 * 作用:
 * 1.从Redis中查询店铺数据;
 * 2.判断缓存是否命中;
 * 3.缓存命中,直接返回店铺数据;
 * 4.缓存未命中,从数据库中查询店铺数据;
 * 5.判断数据库是否存在店铺数据;
 *
 * @param id业务id
 * @return处理结果
 */
@Override
public Result queryById(Long id) {
    //1.从Redis中查询店铺数据
    String cacheKey = CACHE_SHOP_KEY_PREFIX + id;
    String shopJson = stringRedisTemplate.opsForValue().get(cacheKey);
    //2.判断缓存是否命中
    if (StrUtil.isNotBlank(shopJson)) {
        //3.缓存命中,直接返回店铺数据
        Shop shop = JSONUtil.toBean(shopJson, Shop.class);
        return Result.ok(shop);
    }
    //4.缓存未命中,从数据库中查询店铺数据
    Shop shop = getById(id);
    //5.判断数据库是否存在店铺数据
    if (shop == null) {
        //6.数据库中不存在,返回失败信息
        return Result.fail("店铺不存在");
    }
    //7.数据库中存在,重建缓存,并返回店铺数据
    stringRedisTemplate.opsForValue().set(cacheKey, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
    return Result.ok(shop);
}
  • 根据id修改店铺时,先修改数据库,再删除缓存。
java
/**
 * 更新商铺并删除缓存。
 *
 * 作用:
 * 1.更新数据库;
 * 2.删除缓存;
 *
 * @param shop商铺对象
 * @return处理结果
 */
@Override
@Transactional
public Result update(Shop shop) {
    Long id=shop.getId();
    if(id==null){
        return Result.fail("店铺不存在");
    }
    //1.更新数据库
    updateById(shop);
    //2.删除缓存
    stringRedisTemplate.delete(CACHE_SHOP_KEY+shop.getId());  //id可能不存在,所以要去判断
    return Result.ok();
}