@Service public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService { @Autowired private StringRedisTemplate stringRedisTemplate; @Override public List<ShopType> queryTypeList() { String key = CACHE_SHOP_TYPE; //在缓存中查询数据 List<String> stringList = stringRedisTemplate.opsForList().range(key, 0, -1); //判断是否查询到数据 if (!stringList.isEmpty()) { //查询到,返回结果 List<ShopType> shopTypes = stringList.stream().map(s -> { ShopType shopType = JSONUtil.toBean(s, ShopType.class); return shopType; }).collect(Collectors.toList()); return shopTypes; } //没有查询到,查询数据库 List<ShopType> typeList = query().list(); //判断数据库的结果如何 if (typeList.isEmpty()) { //是空,返回错误 return null; } //不为空,添加缓存数据 List<String> jsonStringList = typeList.stream() .map(shopType -> JSONUtil.toJsonStr(shopType)) .collect(Collectors.toList()); stringRedisTemplate.opsForList().rightPushAll(key, jsonStringList); return typeList; }
黑马p37redis实战篇,商品查询缓存代码展示
最新推荐文章于 2024-05-20 20:36:44 发布