@Resource
private StringRedisTemplate stringRedisTemplate;
@GetMapping("/{id}")
public Result queryShopById(@PathVariable("id") Long id) {
Shop shop;
// 1. 查询redis缓存
String str_shop = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
// 2. 判断是否存在
if (StrUtil.isNotBlank(str_shop)) {
System.out.println("go cache " + id);
shop = JSONUtil.toBean(str_shop, Shop.class);
return Result.ok(shop);
}
// 3. 不存在从数据库查询
shop = shopService.getById(id);
if(shop == null) {
return Result.fail("店铺不存在");
}
// 4. 在放到缓存中去
str_shop = JSONUtil.toJsonStr(shop);
stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, str_shop, CACHE_SHOP_TTL, TimeUnit.MINUTES);
return Result.ok(shop);
}
<aside> 💡 反序列化对象:JSONUtil.toBean(str_shop, Shop.class); 序列化对象:JSONUtil.toJsonStr(shop);
</aside>
@GetMapping("list")
public Result queryTypeList() {
List<ShopType> typeList;
List<String> sList = stringRedisTemplate.opsForList().range("cache:shop-type:list", 0, -1);
// 1. 判断缓存中是否存在
if(!sList.isEmpty()) {
System.out.println("go cache list");
typeList = sList.stream().map((item) -> {
return JSONUtil.toBean(item, ShopType.class);
}).collect(Collectors.toList());
return Result.ok(typeList);
}
// 2. 如果不存在查询MySQL
typeList = typeService.query().orderByAsc("sort").list();
// 3. 添加数据库
sList = typeList.stream().map(JSONUtil::toJsonStr).collect(Collectors.toList());
for(String s: sList) {
stringRedisTemplate.opsForList().leftPush("cache:shop-type:list", s);
}
return Result.ok(typeList);
}