解决Redis序列化Java8的LocalDateTime问题

在从Redis获取带有LocalDateTime类型属性的对象时,产生序列化和反序列化问题解决办法
方式一:实体类上指定LocalDateTime的序列化器和反序列化器

  @JsonDeserialize(using = LocalDateTimeDeserializer.class)  //反序列化
  @JsonSerialize(using = LocalDateTimeSerializer.class)  //序列化
  private LocalDateTime birthday;

方式二:在Redis的配置类中指明序列化的方式

  @Configuration
    public class RedisConfig {
    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    private static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("HH:mm:ss");

    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);

        /**
         * JSON序列化
         */
        Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper mapper = new ObjectMapper();
        //取消时间转换格式,默认是时间戳,同时需要设置要表现的时间格式
        mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        mapper.configure(SerializationFeature.WRITE_DURATIONS_AS_TIMESTAMPS, false);
        mapper.setDateFormat(new SimpleDateFormat("yyy-MM-dd HH:mm:ss"));

        //默认序列化没有实现,反序列化有实现
        JavaTimeModule javaTimeModule = new JavaTimeModule();

        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DATE_TIME_FORMATTER));
//        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DATE_FORMATTER));
//        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(TIME_FORMATTER));

        mapper.registerModule(javaTimeModule);
        //设置时区
        mapper.setTimeZone(TimeZone.getDefault());
        //设置格式化输出
//        MAPPER.enable(SerializationFeature.INDENT_OUTPUT);
        //设置格式化输出
        mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        serializer.setObjectMapper(mapper);

//        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        template.setKeySerializer(serializer);
        template.setHashKeySerializer(serializer);
        template.setValueSerializer(serializer);
        template.setHashValueSerializer(serializer);
        return template;
    }
}

Good Mai http://www.goodmai.com/

你可能感兴趣的:(redis)