stefan.stt
stefan.stt

Reputation: 2627

Redis unable to deserialize object

I have added Redis caching to my project and the caching works itself, but loading the cached value fails with the following exception:

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 ....

Caching configurations

@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;
    }

}

Caching ussage

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

Note: FilterOptionsDto implements serializable. I found out that the serialised value is saved to the redis db, but whenever spring tries to deserialize it back, it fails.

Similar question: Problem in deserialize redis-cache to objects in Spring-boot

Upvotes: 2

Views: 1948

Answers (1)

stefan.stt
stefan.stt

Reputation: 2627

The solution is strange, but simple - remove devtools dependency.

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

Upvotes: 2

Related Questions