重温复习redis,要将对象集合存入redis作为缓存,上网找了个json串转集合的工具类,这里记录一下。
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;
public class JsonUtil {
private static ObjectMapper objectMapper = new ObjectMapper();
static {
//忽略属性为null
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
//忽略多余属性
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
public static String objectToString(Object object) {
try {
return objectMapper.writeValueAsString(object);
} catch (JsonProcessingException e) {
// TODO: handle exception
}
return null;
}
public static <T> T stringToObject(String json,Class<T> object) throws IOException {
return objectMapper.readValue(json,object);
}
public static <T> List<T> stringToList(String json,Class<T> object){
try {
CollectionType listType = objectMapper.getTypeFactory().constructCollectionType(ArrayList.class, object);
List<T> list = objectMapper.readValue(json, listType);
return list;
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
}
一个很简单的示例,先从redis中去找集合。若不存在就从数据库中读取集合,并将数据写入redis。
public List<ShopType> queryTypeList() {
String key=CACHE_SHOP_TYPE;
String typeListJson = stringRedisTemplate.opsForValue().get(key);
List<ShopType> typeList=null;
if(typeListJson!=null){//redis中存有集合,直接获取
typeList= JsonUtil.stringToList(typeListJson,ShopType.class);
}else {
//从数据库查找集合
typeList = this.query().orderByAsc("sort").list();
//将集合存入redis
String json = JsonUtil.objectToString(typeList);
stringRedisTemplate.opsForValue().set(key,json);
}
return typeList;
}