problem analysis
When using Redis to cache entity classes containing LocalDateTime type variables, there will be serialization problems. This is because Java 8 does not support the LocalDateTime type by default, so serializers and deserializers need to be added.
error message
write error
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
read error
org.springframework.data.redis.serializer.SerializationException: Could not read 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
Solution
Add the two annotations @JsonSerialize and @JsonDeSerialize above the entity class LocalDateTime type variable
@JsonSerialize(using = LocalDateTimeSerializer.class)//序列化器
@JsonDeserialize(using = LocalDateTimeDeserializer.class)//反序列化器
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")//时间格式(含有日期和时间)
private LocalDateTime createTime;
@JsonSerialize(using = LocalDateSerializer.class)//序列化器
@JsonDeserialize(using = LocalDateDeserializer.class)//反序列化器
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")//时间格式(仅有日期)
private LocalDateTime createTime;
@JsonSerialize(using = LocalTimeSerializer.class)//序列化器
@JsonDeserialize(using = LocalTimeDeserializer.class)//反序列化器
@JsonFormat(pattern = "HH:mm:ss", timezone = "GMT+8")//时间格式(仅有时间)
private LocalDateTime createTime;