Java如何将List集合类型存放到Redis

在Java中我们通常将List存储到redis中,通常有两种方法:

  • 通过Redis中的List数据类型存储,其核心就是通过opsForList()

    public static void main(String[] args) {
        List studentsAll = new ArrayList<>();
        StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
        List students = new ArrayList<>();
        for (Student students : students) {
            stringRedisTemplate.opsForList().rightPush("student", JSON.toJSONString(students));
        }
        List 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  List toListOfObject(String json, Class clazz, ObjectMapper om) {
            try {
                @SuppressWarnings("unchecked") Class arrayClass = (Class) 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 studentsAll = new ArrayList<>();
    StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
    List students = new ArrayList<>();
    // 将student集合存放到redis中
    stringRedisTemplate.opsForValue().set("student",JSON.toJSONString(students));
    // 获取student对象
    String student = stringRedisTemplate.opsForValue().get("student");
    // 解析对象
    List st = JsonUtils.toListOfObject(student, Student.class);
    

你可能感兴趣的:(Java如何将List集合类型存放到Redis)