redisTemplate序列化java8 时间类Instant报错Java 8 date/time type `java.time.Instant` not supported by default

redisTemplate Jackson 序列化Java8 Instant时会出现报错:
Java 8 date/time type java.time.Instant not supported by default: add Module “com.fasterxml.jackson.datatype:jackson-datatype-jsr310” to enable handling

按照提示新增依赖:

<dependency>
    <groupId>com.fasterxml.jackson.datatypegroupId>
    <artifactId>jackson-datatype-jsr310artifactId>
    <version>2.14.2version>
dependency>

依然报错

原因是RedisConfig中进行了序列化配置:

@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
    RedisTemplate<String, Object> template = new RedisTemplate<>();
    template.setConnectionFactory(factory);
    Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
    // ---------------------------
    ObjectMapper om = new ObjectMapper();
    
    // 其他配置...
    return template;
}

需要在这里将ObjectMapper注册JavaTimeModule:

@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
    RedisTemplate<String, Object> template = new RedisTemplate<>();
    template.setConnectionFactory(factory);
    Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
    // ---------------------------
    ObjectMapper om = JsonMapper.builder()
                .addModule(new JavaTimeModule())
                .build();
    
    // 其他配置...
    return template;
}

问题解决

你可能感兴趣的:(java,jvm,开发语言)