RedisTemplate 的序列化 和 反序列化的问题?

//redis配置
        RedisStandaloneConfiguration redisConfiguration = new RedisStandaloneConfiguration("xxx.xx.xx.xx",6379);
        redisConfiguration.setDatabase(0);
        redisConfiguration.setPassword("xxxxx");

        //连接池配置
        GenericObjectPoolConfig<RedisConnectionFactory> genericObjectPoolConfig = new GenericObjectPoolConfig<>();
        genericObjectPoolConfig.setMaxIdle(10);
        genericObjectPoolConfig.setMinIdle(10);
        genericObjectPoolConfig.setMaxTotal(20);
        genericObjectPoolConfig.setMaxWaitMillis(3000);

        // redis客户端配置
        LettucePoolingClientConfiguration.LettucePoolingClientConfigurationBuilder
                builder =  LettucePoolingClientConfiguration.builder().
                commandTimeout(Duration.ofMillis(3000));

        builder.shutdownTimeout(Duration.ofMillis(3000));
        builder.poolConfig(genericObjectPoolConfig);
        LettuceClientConfiguration lettuceClientConfiguration = builder.build();

        // 根据配置和客户端配置创建连接
        LettuceConnectionFactory lettuceConnectionFactory = new LettuceConnectionFactory(redisConfiguration,lettuceClientConfiguration);
        lettuceConnectionFactory.afterPropertiesSet();
        RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();

        redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<>(Object.class));
        AllocationDTO dto = new AllocationDTO();
        dto.setNumber(10);
        dto.setOperator("123456");
        dto.setInId(10);
        redisTemplate.setConnectionFactory(lettuceConnectionFactory);
        redisTemplate.afterPropertiesSet();
        redisTemplate.opsForValue().set("test",dto,10,TimeUnit.SECONDS);
        Object value = redisTemplate.opsForValue().get("test");
        System.out.println(value);

以上是我的RedisTempate的配置信息,我存入的是一个AllocationDTO.class对象,但是在取出的时候,确变成了LinkedHashMap对象image.png,我希望能够让获取到的对象直接是 AllocationDTO.class 而不需要再次做任何转换,请问这种应该如何配置实现呢? 存储的class不国定,所以设置默认类型 可能不能够做到通用

阅读 7.9k
2 个回答

正好在看相关的知识点:

  • Jackson2JsonRedisSerializer是需要每个缓存都要指定具体的类的:
redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<AllocationDTO>(AllocationDTO.class));
  • 可以试试GenericJackson2JsonRedisSerializer作为序列化类,这个在缓存中存储相关类名,所以不需要每个缓存都指定具体类。
  • 如果不是为了可视化方便,也可以直接用默认的JdkSerializationRedisSerializer序列化类。
  • 由于手头上没有相关条件,上述都是看文章后的理论总结,未进行实际实验,楼主可以试验然后告知下是否正确

参考:跨工程Redis缓存的序列化问题

Jackson2JsonRedisSerializer内部的ObjectMapper貌似默认不会保存Class信息到序列化的json串中,需要手动进行替换

Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题