黑马点评---给查询店铺的缓存添加超时剔除和主动更新的策略

修改ShopController中的业务逻辑,满足以下两个需求:

1、根据id查询店铺时,如果缓存未命中,则查询数据库,将数据库结果写入缓存,并设置超时时间

java 复制代码
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryById(Long id) {
        //1.从redis查商铺缓存
        String key =CACHE_SHOP_KEY + id;
        String shopJson = stringRedisTemplate.opsForValue().get(key);

        //2.判断是否存在 如果不为空(存在)
        if(StrUtil.isNotBlank(shopJson)){
            //3.存在,直接返回
            //反序列化json
            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),CACHE_SHOP_TTL, TimeUnit.MINUTES);

        //7.返回
        return Result.ok(shop);
    }
}

2、根据id修改店铺时,先修改数据库,再删除缓存

java 复制代码
    @PutMapping
    public Result updateShop(@RequestBody Shop shop) {
        // 写入数据库
//        shopService.updateById(shop);
        return shopService.update(shop);
    }
 
java 复制代码
  @Override
    @Transactional
    public Result update(Shop shop) {
        Long id = shop.getId();
        if(id == null){
            return Result.fail("店铺id不能为空");
        }
        //写入数据库
        updateById(shop);
        //删除缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY + id);

        return Result.ok();
    }
    
相关推荐
轻揉小乔 真新人1 天前
使用memc-nginx和srcache-nginx模块构建高效透明的缓存机制
运维·nginx·缓存
小园子的小菜1 天前
Redis 核心原理深度解析:从数据结构、IO 模型到持久化机制
数据库·redis·缓存
BullSmall2 天前
Another Redis Desktop Manager(ARDM)下载指南
数据库·redis·缓存
nvd112 天前
ArgoCD 双层轮询深入拆解:从 redis-app.yaml 注册到缓存重建的完整链路
redis·缓存·argocd
xiaoxiangsiyan2 天前
LNMP + Redis Sentinel 高可用架构部署手册(续)
运维·网络·数据库·redis·缓存·架构·sentinel
難釋懷2 天前
Nginx外置缓存-redis2-nginx-module
nginx·缓存·junit
LearnYard2 天前
Android存储空间清理策略对比:缓存识别与多种清理方案的技术分析
缓存·智能手机
时空自由民.2 天前
STM32的缓存Cache
stm32·嵌入式硬件·缓存
Sam_Deep_Thinking2 天前
如何维持缓存的一致性?
java·缓存·面试·程序员·系统架构
ai_coder_ai3 天前
分布式缓存架构设计与实践
分布式·缓存