Redis-商品查询缓存02-添加商品类型缓存


以字符串形式存储

ShopTypeController.java

1
2
3
4
@GetMapping("list")
public Result queryTypeList() {
return typeService.queryTypeList();
}

ShopTypeServiceImpl.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
* 服务实现类
*/
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

@Resource
private StringRedisTemplate stringRedisTemplate;
@Autowired
private IShopTypeService shopTypeService;

@Override
public Result queryTypeList() {
// 从 redis 中查询商品类别
String shopTypeList = stringRedisTemplate.opsForValue().get(SHOP_TYPE_KEY);
// 判断redis是否存在
if (StrUtil.isNotBlank(shopTypeList)) {
// 存在,直接返回
List<ShopType> list = JSONUtil.toList(shopTypeList, ShopType.class);
return Result.ok(list);
}
// redis中 不存在的情况
List<ShopType> typeList = shopTypeService
.query().orderByAsc("sort").list();
if (typeList==null) {
return Result.fail("店铺不存在!");
}
// 数据库中存在, 写入redis中
stringRedisTemplate.opsForValue().set(SHOP_TYPE_KEY, JSONUtil.toJsonStr(typeList));
stringRedisTemplate.expire(SHOP_TYPE_KEY, SHOP_TYPE_TTL, TimeUnit.MINUTES);
return Result.ok(typeList);
}
}