存放redis异常Could not write JSON: Java 8 date/time type `java.time.LocalDateTime处理

1.首先需要maven引入

            jackson-datatype-jsr310
            com.fasterxml.jackson.datatype
            2.15.3
 

        2.示例代码如下

  private RedisTemplate serializer(RedisTemplate redisTemplate) {
        // LocalDate序列化
        ObjectMapper mapper = new ObjectMapper();
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        // 设置序列化格式
        javaTimeModule.addSerializer(LocalDateTime.class,
                new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        mapper.registerModule(javaTimeModule);
        // 使用 FastJsonRedisSerializer 来序列化和反序列化redis 的 value的值
        Jackson2JsonRedisSerializer fastJsonRedisSerializer = new Jackson2JsonRedisSerializer<>(mapper,Object.class);
        // key 的 String 序列化采用 StringRedisSerializer
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringRedisSerializer);
        redisTemplate.setHashKeySerializer(stringRedisSerializer);
        // value 的值序列化采用 fastJsonRedisSerializer
        redisTemplate.setValueSerializer(fastJsonRedisSerializer);
        redisTemplate.setHashValueSerializer(fastJsonRedisSerializer);

        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    } 
  

你可能感兴趣的:(java)