难点是泛型如何转换
一、arrayList>转化json字符串,存入redis缓存
ArrayList> listProfit
//将ArrayList>类型数据转换成json字符串
String listProfitPctJsonStr = JSON.toJSONString(listProfit);
//然后将json字符串存入redis缓存,唯一key value
JedisUtils.setex("listProfit", 600,listProfitPctJsonStr);
二、json字符串转回ArrayList>(难点)
List> listProfit=null;
//先从redis里面去查询数据,看是否能获取到对应json字符串
String jsonStrLp=JedisUtils.get("listProfit");
//如果能获取则说明缓存中有数据
if(!StringUtils.isBlank(jsonStrLp)){
//目的是为了泛型的转换
listProfit=new ArrayList>();
//先把从redis缓存中取出来的json字符串转为List集合
List mapList=JSON.parseArray(jsonStrLp, Map.class);
//然后循环遍历这个List集合,得出的结果为Map,然后再强转为Map,
再循环 把 Map添加到List集合中,搞定!!!
for (Map map : mapList) {
Map sObj=(Map)map;
listProfit.add(sObj);
}
补充知识:Java的List和Json转换以及StringRedisTemplate往redis存泛型对象
List转Json
List user= new ArrayList();
String str = JSON.toJSONString(user);
Json 转List方法一
List user= JSON.parseArray(json,User.class);
如果是泛型方法需要使用TypeReference
Json 转List 方法二
String json = "[{}]";
List user= JSON.parseObject(json,new TypeReference>(){});
泛型T
Json 转List方法三
List students = JSON.parseObject(listCache,new TypeReference>(){});
综合例子:Springboot环境下利用StringRedisTemplate往redis存泛型对象
一开始要注入下StringRedisTemplate
@Autowired
private StringRedisTemplate redisTemplate;
Redis获取值不存在就从数据库取出来json化存缓存,存在则直接反序列化json为List
List list;
String listCache=redisTemplate.opsForValue().get(key);
if(listCache!=null){
list = JSON.parseObject(listCache,new TypeReference>(){});
}
else {
list = userService.getAllList();
redisTemplate.opsForValue().set(key, JSON.toJSONString(lis