springboot集成redis,使用jackson序列化方案报Type id handling not implemented for 错误问题处理

使用序列化类:GenericJackson2JsonRedisSerializer

错误信息:

Caused by: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Type id handling not implemented for type java.lang.Object (by serializer of type com.fasterxml.jackson.databind.ser.impl.UnsupportedTypeSerializer) (through reference chain: java.util.ArrayList[0]->xxx.xx.xx.xx["createTime"])
	at com.fasterxml.jackson.databind.exc.InvalidDefinitionException.from(InvalidDefinitionException.java:77) ~[jackson-databind-2.13.3.jar!/:2.13.3]
	at com.fasterxml.jackson.databind.SerializerProvider.reportBadDefinition(SerializerProvider.java:1300) ~[jackson-databind-2.13.3.jar!/:2.13.3]
	at com.fasterxml.jackson.databind.DatabindContext.reportBadDefinition(DatabindContext.java:400) ~[jackson-databind-2.13.3.jar!/:2.13.3]
	at com.fasterxml.jackson.databind.JsonSerializer.serializeWithType(JsonSerializer.java:160) ~[jackson-databind-2.13.3.jar!/:2.13.3]
	at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:730) ~[jackson-databind-2.13.3.jar!/:2.13.3]
	at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:774) ~[jackson-databind-2.13.3.jar!/:2.13.3]
	at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeWithType(BeanSerializerBase.java:657) ~[jackson-databind-2.13.3.jar!/:2.13.3]
	at com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer.serializeTypedContents(IndexedListSerializer.java:181) ~[jackson-databind-2.13.3.jar!/:2.13.3]
	at com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer.serializeContents(IndexedListSerializer.java:92) ~[jackson-databind-2.13.3.jar!/:2.13.3]
	at com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer.serializeContents(IndexedListSerializer.java:18) ~[jackson-databind-2.13.3.jar!/:2.13.3]
	at com.fasterxml.jackson.databind.ser.std.AsArraySerializerBase.serializeWithType(AsArraySerializerBase.java:267) ~[jackson-databind-2.13.3.jar!/:2.13.3]
	at com.fasterxml.jackson.databind.ser.impl.TypeWrappedSerializer.serialize(TypeWrappedSerializer.java:32) ~[jackson-databind-2.13.3.jar!/:2.13.3]
	at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider._serialize(DefaultSerializerProvider.java:480) ~[jackson-databind-2.13.3.jar!/:2.13.3]
	at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:319) ~[jackson-databind-2.13.3.jar!/:2.13.3]
	at com.fasterxml.jackson.databind.ObjectMapper._writeValueAndClose(ObjectMapper.java:4568) ~[jackson-databind-2.13.3.jar!/:2.13.3]
	at com.fasterxml.jackson.databind.ObjectMapper.writeValueAsBytes(ObjectMapper.java:3844) ~[jackson-databind-2.13.3.jar!/:2.13.3]
	at org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer.serialize(GenericJackson2JsonRedisSerializer.java:123) ~[spring-data-redis-2.7.0.jar!/:2.7.0]
	... 30 more

 参考:​​​​​​https://blog.csdn.net/Ellen_Tangxiang/article/details/111310153

参考:json - Jackson serialization failing when upgrading from 2.10 (InvalidDefinitionException: Type id handling not implemented for type java.lang.Object) - Stack Overflow

在参考其他的一些博客后

给到些想法,可以重新定义下 ObjectMapper 对象,使其兼容不可序列化的类型

重写objectMap,然后覆盖默认的


    public ObjectMapper getObjectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
        mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
        mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ISO_DATE_TIME));
        mapper.registerModule(javaTimeModule);
        mapper.registerModule(new Jdk8Module());
        mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        mapper.setTimeZone(Calendar.getInstance().getTimeZone());
//        mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
        mapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
        return mapper;
    }

 public RedisTemplate<String, Object> redisTemplate(int db) {
        //为了开发方便,一般直接使用<String,Object>
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnection(db)); //设置连接

        template.setDefaultSerializer(new StringRedisSerializer());

        // 使用 GenericFastJsonRedisSerializer 替换默认序列化
        //这里覆盖默认的ObjectMapper
        GenericJackson2JsonRedisSerializer genericFastJsonRedisSerializer = new GenericJackson2JsonRedisSerializer(getObjectMapper());
        // 设置key和value的序列化规则
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(genericFastJsonRedisSerializer);
        // 设置hashKey和hashValue的序列化规则
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(genericFastJsonRedisSerializer);
        // 设置支持事物
//        template.setEnableTransactionSupport(true);

        template.afterPropertiesSet();
        return template;
    }

但是经过测时候,解决开篇的报错信息,但是Jackson序列化对象,保存在reids时。保存的完整json数据格式,存入redis的对象信息反序列化后,全部变成了 hashmap接口,导致业务处理报错

java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.xx.xx.xx

j经过查询后 ObjectMapper没有配置DefaultTyping属性,jackson将使用简单的数据绑定具体的java类型,其中Object就会在反序列化的时候变成LinkedHashMap......

再回过头来看下xml中的json序列化实现类

代码编写时发现方法已过期,找到了替代的方法,创建object Mapper,设置 其属性。完全解决了所有问题,代码经过测试

//过期的方法
//        mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);

//替换方法
        mapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个基于Spring BootRedis的键值序列化的示例代码: 首先,在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> </dependency> ``` 然后,在application.properties文件中配置Redis连接信息: ```properties spring.redis.host=127.0.0.1 spring.redis.port=6379 spring.redis.password= spring.redis.database=0 spring.redis.pool.max-active=8 spring.redis.pool.max-wait=-1 spring.redis.pool.max-idle=8 spring.redis.pool.min-idle=0 ``` 接下来,我们可以创建一个RedisConfig类,用于配置RedisTemplate和RedisCacheManager: ```java @Configuration @EnableCaching public class RedisConfig extends CachingConfigurerSupport { @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(factory); // 使用Jackson2JsonRedisSerializer序列化和反序列化redis的value值(默认使用JDK的序列化方式) Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class); ObjectMapper mapper = new ObjectMapper(); mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); serializer.setObjectMapper(mapper); // 设置value的序列化规则和key的序列化规则 template.setValueSerializer(serializer); template.setKeySerializer(new StringRedisSerializer()); template.afterPropertiesSet(); return template; } @Bean public CacheManager cacheManager(RedisConnectionFactory factory) { RedisCacheManager cacheManager = RedisCacheManager.create(factory); cacheManager.setDefaultExpiration(1800); // 设置缓存过期时间(单位:秒) return cacheManager; } } ``` 现在,我们可以在任何需要使用Redis的地方注入RedisTemplate,并使用它来存储和读取数据。例如: ```java @Service public class UserService { @Autowired private RedisTemplate<String, Object> redisTemplate; public User getUserById(Long id) { String key = "user:" + id; User user = (User) redisTemplate.opsForValue().get(key); if (user == null) { // 从数据库中获取用户信息 user = userRepository.findById(id).orElse(null); if (user != null) { redisTemplate.opsForValue().set(key, user); } } return user; } } ``` 在上面的示例中,我们将用户信息存储在Redis中,并设置了一个过期时间。当需要获取用户信息时,首先从缓存中查找,如果缓存中没有,则从数据库中获取,并将结果存储在缓存中,以便下一次使用。这样可以大大提高系统的性能和响应速度。 总结:以上是一个基于Spring BootRedis的键值序列化的示例代码,通过使用Jackson2JsonRedisSerializer序列化和反序列化redis的value值,可以实现最优化最高性能的键值序列化

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值