You've already forked FrameTour-BE
fix(redis): 配置Redis缓存管理器以防止ClassCastException
- 添加BasicPolymorphicTypeValidator以处理多态类型 - 在ObjectMapper中激活默认类型检查 - 更新Redis序列化配置以支持类型安全 - 防止因类型转换导致的运行时异常 - 确保JavaTimeModule与类型检查兼容 - 统一Redis缓存和模板的序列化配置
This commit is contained in:
@@ -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<Object> 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<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(objectMapper, Object.class);
|
||||
|
||||
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
|
||||
|
||||
Reference in New Issue
Block a user