假如我们向redis中存放了一个JSON数组,从中获取的时候需要将JSON数组转化为List集合,然后将List对象返回给前端。
1.引入hutool和fastjson依赖
<!--hutool-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.17</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.66</version>
</dependency>
2.hutool的作用是使用JSONUtil类将数据库查到的List集合转化成JSON数组,存到redis中
List<ShopType> typeList = typeService.query().list();
String typeListJson = JSONUtil.toJsonStr(typeList);
stringRedisTemplate.opsForValue().set("shopList",typeListJson);
3.fastjson的JSONObject类作用是将JSON数组转换成List集合
String shopList = stringRedisTemplate.opsForValue().get("shopList");
List<ShopType> list = JSONObject.parseArray(shopList, ShopType.class);
return Result.ok(list);
完整代码:
@GetMapping("list")
public Result queryTypeList() {
String shopList = stringRedisTemplate.opsForValue().get("shopList");
if(StringUtils.isEmpty(shopList)){
List<ShopType> typeList = typeService
.query().orderByAsc("sort").list();
String typeListJson = JSONUtil.toJsonStr(typeList);
stringRedisTemplate.opsForValue().set("shopList",typeListJson);
return Result.ok(typeList);
}
List<ShopType> list = JSONObject.parseArray(shopList, ShopType.class);
return Result.ok(list);
}
|