SpringBoot Redis反序列化LocalDateTime失败的问题
一个实体类,里面包含了LocalDateTime 类型的属性,把实体类数据存入Redis后变成这样:
createTime就是LocalDateTime类型的属性,当从缓存里获取这个实体类数据时,报错:
2021-11-03 17:29:15.031 ERROR 12732 --- [nio-8080-exec-3] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.data.redis.serializer.SerializationException: Could not read JSON: Cannot construct instance of `java.time.LocalDateTime` (no Creators, like default constructor, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
at [Source: (byte[])"["com.rgb3.qa_community.entity.vo.QuestionVo",{"id":129,"createTime":{"date":{"year":2021,"month":"OCTOBER","day":13,"dayOfMonth":13,"monthValue":10,"dayOfWeek":"WEDNESDAY","era":["java.time.chrono.IsoEra","CE"],"dayOfYear":286,"leapYear":false,"prolepticMonth":24261,"chronology":{"id":"ISO","calendarType":"iso8601"}},"time":{"hour":23,"minute":40,"second":53,"nano":0},"month":"OCTOBER","year":2021,"dayOfMonth":13,"hour":23,"minute":40,"monthValue":10,"nano":0,"second":53,"dayOfWeek":"WEDNESDAY""[truncated 814 bytes]; line: 1, column: 71] (through reference chain: com.rgb3.qa_community.entity.vo.QuestionVo["createTime"]); nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `java.time.LocalDateTime` (no Creators, like default constructor, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
at [Source: (byte[])"["com.rgb3.qa_community.entity.vo.QuestionVo",{"id":129,"createTime":{"date":{"year":2021,"month":"OCTOBER","day":13,"dayOfMonth":13,"monthValue":10,"dayOfWeek":"WEDNESDAY","era":["java.time.chrono.IsoEra","CE"],"dayOfYear":286,"leapYear":false,"prolepticMonth":24261,"chronology":{"id":"ISO","calendarType":"iso8601"}},"time":{"hour":23,"minute":40,"second":53,"nano":0},"month":"OCTOBER","year":2021,"dayOfMonth":13,"hour":23,"minute":40,"monthValue":10,"nano":0,"second":53,"dayOfWeek":"WEDNESDAY""[truncated 814 bytes]; line: 1, column: 71] (through reference chain: com.rgb3.qa_community.entity.vo.QuestionVo["createTime"])] with root cause
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `java.time.LocalDateTime` (no Creators, like default constructor, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
百度了一下,尝试在LocalDateTime类型的属性上加注解指定序列化/反序列化器:
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
@JsonSerialize(using = LocalDateTimeSerializer.class)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime createTime;
再次启动,向缓存里放数据,LocalDateTime的数据显示正常,不会多出很多数据:
重复多次去获取缓存里的数据也没报错了。