From 57be6aa98375207a75620491780318d63f0dde8e Mon Sep 17 00:00:00 2001 From: Jerry Yan <792602257@qq.com> Date: Fri, 28 Nov 2025 13:37:26 +0800 Subject: [PATCH] =?UTF-8?q?fix(redis):=20=E9=85=8D=E7=BD=AERedis=E7=BC=93?= =?UTF-8?q?=E5=AD=98=E7=AE=A1=E7=90=86=E5=99=A8=E4=BB=A5=E9=98=B2=E6=AD=A2?= =?UTF-8?q?ClassCastException?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 添加BasicPolymorphicTypeValidator以处理多态类型 - 在ObjectMapper中激活默认类型检查 - 更新Redis序列化配置以支持类型安全 - 防止因类型转换导致的运行时异常 - 确保JavaTimeModule与类型检查兼容 - 统一Redis缓存和模板的序列化配置 --- .../basic/config/CustomRedisCacheManager.java | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/main/java/com/ycwl/basic/config/CustomRedisCacheManager.java b/src/main/java/com/ycwl/basic/config/CustomRedisCacheManager.java index 6c70b0f2..dcbe1de2 100644 --- a/src/main/java/com/ycwl/basic/config/CustomRedisCacheManager.java +++ b/src/main/java/com/ycwl/basic/config/CustomRedisCacheManager.java @@ -2,6 +2,8 @@ package com.ycwl.basic.config; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import com.fasterxml.jackson.databind.jsontype.BasicPolymorphicTypeValidator; +import com.fasterxml.jackson.databind.jsontype.PolymorphicTypeValidator; import org.springframework.cache.annotation.CachingConfigurerSupport; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; @@ -28,6 +30,13 @@ public class CustomRedisCacheManager extends CachingConfigurerSupport { public RedisCacheConfiguration redisCacheConfiguration() { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.registerModule(new JavaTimeModule()); + + // Configure type handling to prevent ClassCastException + PolymorphicTypeValidator typeValidator = BasicPolymorphicTypeValidator.builder() + .allowIfBaseType(Object.class) + .build(); + objectMapper.activateDefaultTyping(typeValidator, ObjectMapper.DefaultTyping.NON_FINAL); + Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(objectMapper, Object.class); RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig(); @@ -55,6 +64,13 @@ public class CustomRedisCacheManager extends CachingConfigurerSupport { // Configure Jackson2JsonRedisSerializer with JavaTimeModule for value serialization ObjectMapper objectMapper = new ObjectMapper(); objectMapper.registerModule(new JavaTimeModule()); + + // Configure type handling to prevent ClassCastException + PolymorphicTypeValidator typeValidator = BasicPolymorphicTypeValidator.builder() + .allowIfBaseType(Object.class) + .build(); + objectMapper.activateDefaultTyping(typeValidator, ObjectMapper.DefaultTyping.NON_FINAL); + Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(objectMapper, Object.class); redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);