I am using spring-data-redis for caching data in my spring boot app. I am using Mongo as my primary data source and Redis as a cache. When I hit the API for the first time, it fetches record from Mongo and saves it in Cache, and returns MyObject correctly to the client. But when I hit the API second time, it finds the record in the Cache, and while trying to deserialize that back into MyObject, it . always runs into a cast exception:
java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to MyObject
Here is my Redis Configuration:
public class MyConfiguration {
@Bean
public CacheManager cacheManager(RedisTemplate<String, MyObject> redisTemplate) {
return new RedisCacheManager(redisTemplate);
}
@Bean
public RedisTemplate<String, MyObject> redisTemplate(RedisConnectionFactory connectionFactory, ObjectMapper objectMapper) {
StringRedisSerializer serializer = new StringRedisSerializer();
GenericJackson2JsonRedisSerializer hashValueSerializer = new GenericJackson2JsonRedisSerializer(objectMapper);
RedisTemplate<String, MyObject> redisTemplate = new RedisTemplate<>();
redisTemplate.setKeySerializer(serializer);
redisTemplate.setValueSerializer(hashValueSerializer);
redisTemplate.setConnectionFactory(connectionFactory);
return redisTemplate;
}
}
Found same problem reported here: Spring-data-redis @Cacheable java.lang.ClassCastException: java.util.HashMap cannot be cast to java.lang.String
I researched for quite some time but have no ideas. Please suggest. Thanks a ton in advance.