需求描述:需要对店铺分类ShopType查询并放入Redis中进行缓存优化,需要将查询结果 List类型转为字符串放到redis中,并且还要能从redis中获取并解析为list
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
@Resource
StringRedisTemplate stringRedisTemplate;
@Override
public List<ShopType> queryShopTypeList() {
//查询是否有缓存
String key = CACHE_SHOPTYPE;
//缓存存在,则直接返回缓存
String shopTypeListStr = stringRedisTemplate.opsForValue().get(key);
if(shopTypeListStr != null){
List<ShopType> shopTypes = JSONObject.parseArray(shopTypeListStr, ShopType.class);
return shopTypes;
}
//没有缓存,就先写到缓存中,再返回
List<ShopType> shopTypeList = this.list();
stringRedisTemplate.opsForValue().set(key, JSONObject.toJSONString(shopTypeList));
return shopTypeList;
}
}
其中List类型和redis中字符串类型互转使用fastjson工具中的JSONObject类
//List转为JSON
JSONObject.toJSONString(shopTypeList)
//JSON解析为List
List<ShopType> shopTypes = JSONObject.parseArray(shopTypeListStr, ShopType.class);
记得导入fastjson依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.33</version>
</dependency>