Redis反序列化LocalDateTime时报错

今天在整合redis和spring boot的时候,遇到了一个错误,记录一下。

报错如下:

Could not read JSON: Cannot construct instance of `java.time.LocalDateTime` (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator)

查看后发现是数据从redis中取出时,Jackson2反序列化数据处理LocalDateTime类型时出错,原因是:Jackson2在序列化LocalDateTime时输出的不是普通的字符串时间格式,而是如下所示的格式(普通时间格式:2019-02-27 12:10:17)

{
    "date": {
        "year": 2019,
        "month": "FEBRUARY",
        "day": 27,
        "dayOfMonth": 27,
        "dayOfWeek": "WEDNESDAY",
        "era": [
            "java.time.chrono.IsoEra",
            "CE"
        ],
        "dayOfYear": 58,
        "leapYear": false,
        "chronology": {
            "id": "ISO",
            "calendarType": "iso8601"
        },
        "prolepticMonth": 24229,
        "monthValue": 2
    },
    "time": {
        "hour": 12,
        "minute": 10,
        "second": 17,
        "nano": 0
    },
    "month": "FEBRUARY",
    "year": 2019,
    "dayOfMonth": 27,
    "dayOfWeek": "WEDNESDAY",
    "dayOfYear": 58,
    "hour": 12,
    "minute": 10,
    "nano": 0,
    "second": 17,
    "monthValue": 2,
    "chronology": [
        "java.time.chrono.IsoChronology",
        {
            "id": "ISO",
            "calendarType": "iso8601"
        }
    ]
}

 

 

所以是Jackson2序列化LocalDateTime跟我们所预想的不一致,将注册给redis的序列化模板修改成以下就行

@Configuration
public class RedisConfig {

    /**
     * 定义 UserRedisTemplate ,指定序列化和反序列化的处理类
     *
     * @param factory redis连接工厂
     * @return 模板
     */
    @Bean("UserRedisTemplate")
    public RedisTemplate<String, User> userRedisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, User> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        Jackson2JsonRedisSerializer<User> j2jrs = new Jackson2JsonRedisSerializer<>(User.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // 解决jackson2无法反序列化LocalDateTime的问题
        om.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        om.registerModule(new JavaTimeModule());
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY); j2jrs.setObjectMapper(om);
// 序列化 value 时使用此序列化方法 template.setValueSerializer(j2jrs); template.setHashValueSerializer(j2jrs); // 序列化 key 时 StringRedisSerializer srs = new StringRedisSerializer(); template.setKeySerializer(srs); template.setHashKeySerializer(srs); template.afterPropertiesSet(); return template; } }

 

 

主要是加上标红的那两句

 

posted @ 2021-12-13 21:43  牧之丨  阅读(279)  评论(0编辑  收藏  举报