基于Redis添加商铺查询缓存

时间:2025-03-21 07:11:50
public Result queryById(Long id) { // 1.从redis中查询店铺缓存 String shopJson = stringRedisTemplate.opsForValue().get("cache:shop:"+id); // 2.判断缓存是否存在 if (StrUtil.isNotBlank(shopJson)) { Shop shop = JSONUtil.toBean(shopJson, Shop.class); return Result.ok(shop); } // 3.不存在,根据id查询数据库 Shop shop = getById(id); // mybatisplus功能 // 4.不存在,返回错误 if (shop == null) { return Result.fail("店铺数据不存在"); } // 存在,写入redis stringRedisTemplate.opsForValue().set("cache:shop:"+id, JSONUtil.toJsonStr(shop)); return Result.ok(shop); }