Video in progress
What serialization problems do you run into when storing @Cacheable results in Redis?
The default JDK serializer requires the class to be Serializable, writes binary, and can't read the data back when the class changes. A JSON serializer gives a readable format, but you have to think about type information, generics, and compatibility between old and new versions during a deploy.
📖 Answer
The usual story: spring-boot-starter-data-redis is added, @Cacheable("products") is put on, and the first error is SerializationException because the DTO isn't Serializable. You add it and it works. On the next deploy you add a field to the DTO, and the new pod can't read the cache written by the old pods (serialVersionUID doesn't match).
The better way is JSON with an explicit type for each cache:
@Bean
RedisCacheManagerBuilderCustomizer cacheCustomizer(ObjectMapper mapper) {
var productSerializer = new Jackson2JsonRedisSerializer<>(mapper, ProductDto.class);
return builder -> builder.withCacheConfiguration("products",
RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(10))
.prefixCacheNameWith("v2:")
.serializeValuesWith(RedisSerializationContext.SerializationPair
.fromSerializer(productSerializer)));
}
The problems that come next:
GenericJackson2JsonRedisSerializerwrites an@classfield into the JSON. It's convenient, but if you move the class to another package the old entries can't be read, and it also relies on Jackson default typing, so be careful.- Generic types. For a method returning
List<ProductDto>, the type can get lost, aLinkedHashMapcomes back, and aClassCastExceptionfollows. Wrap the list in a wrapper record or give the serializer an explicitJavaType. - Version prefix. If the DTO changes incompatibly, change the prefix (
v2:); the old entries expire on their own with the TTL. - A deserialization error shouldn't turn the endpoint into a 500: swallow the get error in a
CacheErrorHandler, treat it as a "miss" and read from the source. - Cache DTOs, not entities: Hibernate proxies and lazy fields cause problems in serialization.
Sign up to mark studied questions and save your progress.