spring-boot - Redis无法反序列化对象

标签 spring-boot caching redis

我已将 Redis 缓存添加到我的项目中,并且缓存可以自行工作,但加载缓存值失败,并出现以下异常:

java.lang.ClassCastException: class com.dto.FilterOptionsDto cannot be cast to class 
com.dto.FilterOptionsDto (com.dto.FilterOptionsDto is in unnamed module of loader 'app'; 
com.dto.FilterOptionsDto is in unnamed module of loader org.springframework.boot.devtools.restart.classloader.RestartClassLoader @3d0da857)
at ....

缓存配置

@Configuration
@EnableConfigurationProperties({CacheProperties.class})
public class RedisConfig {

    @Bean
    RedisCacheManagerBuilderCustomizer redisCacheManagerBuilderCustomizer(CacheProperties cacheProperties) {
        return builder -> {
            Map<String, RedisCacheConfiguration> configurationMap = new HashMap<>();
            configurationMap.put(CacheNames.IDP_USER_PROFILES, RedisCacheConfiguration.defaultCacheConfig()
                    .entryTtl(Duration.ofSeconds(cacheProperties.getIdpUserProfilesTtlSeconds())));
            configurationMap.put(CacheNames.STIBO_STORES_FILTER_OPTIONS, RedisCacheConfiguration.defaultCacheConfig()
                    .entryTtl(Duration.ofSeconds(cacheProperties.getIdpUserProfilesTtlSeconds())));
            builder.withInitialCacheConfigurations(configurationMap);
        };
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate() {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(new LettuceConnectionFactory());
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        return redisTemplate;
    }

}

缓存使用

    @Override
    @Cacheable(value = CacheNames.STIBO_STORES_FILTER_OPTIONS)
    public FilterOptionsDto getStoresFilterOptions(CountryEnum country, boolean includeClosedStores, boolean includeSingleOptions) {

注意:FilterOptionsDto 实现了可序列化。我发现序列化的值被保存到redis数据库中,但是每当spring尝试将其反序列化回来时,它就会失败。

类似问题:Problem in deserialize redis-cache to objects in Spring-boot

最佳答案

解决方案很奇怪,但很简单 - 删除 devtools 依赖项。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <optional>true</optional>
</dependency>

关于spring-boot - Redis无法反序列化对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64537394/

相关文章:

java - 如何在 Spring Security 中禁用 'X-Frame-Options' 响应 header ?

java - 使用 HTTP Basic 和 OIDC Bearer Token 的 Spring Security 身份验证

java - Spring boot 集成测试观察服务的困境

java - Ignite cursor.getAll() 需要很长时间来检索数据

python - 如何确定lru_cache所需的maxsize?

java - 如何将自己的执行器传递给redis lettuce库?

spring - 如果应用程序无法启动,是否有可能导致快速 Spring 测试失败?

android - Volley.newRequestQueue 导致 OutOfMemoryError

javascript - 我应该如何编写简单的顺序 GET?

mysql - 用于创建用户段的最佳数据库结构