目录

今日说码

点滴记录中国代码进程

X

Redis 序列化 LocalDateTime 异常

问题

  向redis中数据存取实体类时出现序列化异常:

org.springframework.data.redis.serializer.SerializationException: Could not write JSON: Java 8 date/time type `java.time.LocalDateTime` not supported by default: add Module "com.fasterxml.jackson.datatype:jackson-datatype-jsr310" to enable handling (through reference chain: com.example.hxyhb.entity.HxyhbMuser["created"]); nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Java 8 date/time type `java.time.LocalDateTime` not supported by default: add Module "com.fasterxml.jackson.datatype:jackson-datatype-jsr310" to enable handling (through reference chain: com.example.hxyhb.entity.HxyhbMuser["created"])
at org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer.serialize(Jackson2JsonRedisSerializer.java:88) ~[spring-data-redis-2.6.0.jar:2.6.0]
at org.springframework.data.redis.core.AbstractOperations.rawHashValue(AbstractOperations.java:186) ~[spring-data-redis-2.6.0.jar:2.6.0]
at org.springframework.data.redis.core.DefaultHashOperations.putAll(DefaultHashOperations.java:209) ~[spring-data-redis-2.6.0.jar:2.6.0]

原因

  数据向redis中存入时进行序列化,取出时进行反序列化,即Serialize和Deserialize。项目中我使用的序列化器是 Jackson2JsonRedisSerializer由于无法处理LocalDateTime的数据类型,所以会出现序列化异常。

@Bean
public RedisTemplate<String, Object> redisTemplate() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    mapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
    Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
    jackson2JsonRedisSerializer.setObjectMapper(mapper);

    // 设置key和value的序列化规则
    RedisTemplate<String, Object> template = new RedisTemplate<>();
    StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
    template.setKeySerializer(stringRedisSerializer);
    template.setHashKeySerializer(stringRedisSerializer);
    template.setValueSerializer(jackson2JsonRedisSerializer);
    template.setHashValueSerializer(jackson2JsonRedisSerializer);
    template.setDefaultSerializer(jackson2JsonRedisSerializer);
    template.afterPropertiesSet();
    return template;
}

解决方案

  在实体类中LocalDateTime类型的字段上添加@JsonSerialize(using = LocalDateTimeSerializer.class)、@JsonDeserialize(using = LocalDateTimeDeserializer.class)注解,指定序列化器与反序列化器。

@TableField("created")
@JsonSerialize(using = LocalDateTimeSerializer.class)
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
private LocalDateTime created;

标题:Redis 序列化 LocalDateTime 异常
作者:96XL
地址:https://solo.96xl.top/articles/2021/12/30/1640857059104.html