在Java中我们通常将List存储到redis中,通常有两种方法:
-
通过Redis中的List数据类型存储,其核心就是通过
opsForList()
public static void main(String[] args) { List<Student> studentsAll = new ArrayList<>(); StringRedisTemplate stringRedisTemplate = new StringRedisTemplate(); List<Student> students = new ArrayList<>(); for (Student students : students) { stringRedisTemplate.opsForList().rightPush("student", JSON.toJSONString(students)); } List<String> studentList = stringRedisTemplate.opsForList() .range("student", 0, -1); // 将redis中的数据转换为对象集合 for (String studentString : studentList) { studentsAll.add(BeanUtils.copyProperties(studentString,Student.class)); } }
-
实际上还可以通过
ObjectMapper
方法public class JsonUtils{ private static final ObjectMapper om = createObjectMapper(); public static ObjectMapper createObjectMapper() { ObjectMapper om = new ObjectMapper(); // 反序列化时,忽略Javabean中不存在的属性,而不是抛出异常 om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // 忽略入参没有任何属性导致的序列化报错 om.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS,false); return om; } public static <T> List<T> toListOfObject(String json, Class<T> clazz, ObjectMapper om) { try { @SuppressWarnings("unchecked") Class<T[]> arrayClass = (Class<T[]>) Class .forName("[L" + clazz.getName() + ";"); return Lists.newArrayList(om.readValue(json, arrayClass)); } catch (IOException | ClassNotFoundException e) { log.error("json={}, clazz={}", json, clazz, e); throw new JsonException(e); } } }
List<Student> studentsAll = new ArrayList<>(); StringRedisTemplate stringRedisTemplate = new StringRedisTemplate(); List<Student> students = new ArrayList<>(); // 将student集合存放到redis中 stringRedisTemplate.opsForValue().set("student",JSON.toJSONString(students)); // 获取student对象 String student = stringRedisTemplate.opsForValue().get("student"); // 解析对象 List<Student> st = JsonUtils.toListOfObject(student, Student.class);