spring-boot
redis
cache
serializer
configuration

Configure a new serializer for spring-boot redis cache config

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Spring Boot's Redis cache support lets you control how cache keys and values are serialized before they are stored in Redis. Changing the serializer is a common customization when you want JSON instead of JDK serialization, better interoperability, or safer cache payloads. The usual solution is to customize RedisCacheConfiguration and provide a different value SerializationPair.

Why Change the Default Serializer

Serializer choice affects more than storage format. It also affects:

  • readability of cached data
  • compatibility across services
  • ability to evolve classes over time
  • security and operational risk

JDK serialization is often avoided for cache values because it is Java-specific and opaque. JSON-based serializers are popular because the payloads are easier to inspect and less tightly coupled to one JVM class shape.

Configure JSON Value Serialization

A common Spring Boot setup uses GenericJackson2JsonRedisSerializer for cache values.

java
1import org.springframework.cache.annotation.EnableCaching;
2import org.springframework.context.annotation.Bean;
3import org.springframework.context.annotation.Configuration;
4import org.springframework.data.redis.cache.RedisCacheConfiguration;
5import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
6import org.springframework.data.redis.serializer.RedisSerializationContext;
7
8@Configuration
9@EnableCaching
10public class CacheConfig {
11
12    @Bean
13    RedisCacheConfiguration redisCacheConfiguration() {
14        return RedisCacheConfiguration.defaultCacheConfig()
15            .serializeValuesWith(
16                RedisSerializationContext.SerializationPair.fromSerializer(
17                    new GenericJackson2JsonRedisSerializer()
18                )
19            );
20    }
21}

With that bean in place, Spring Boot uses the customized cache configuration for the Redis cache manager it auto-configures.

Keys and Values Are Configured Separately

Most cache setups leave keys as strings and customize only the values. That is usually sensible because cache keys are operational identifiers, while values hold the actual serialized object graph.

If you need to customize both, you can do so explicitly:

java
1import org.springframework.data.redis.serializer.StringRedisSerializer;
2
3return RedisCacheConfiguration.defaultCacheConfig()
4    .serializeKeysWith(
5        RedisSerializationContext.SerializationPair.fromSerializer(
6            new StringRedisSerializer()
7        )
8    )
9    .serializeValuesWith(
10        RedisSerializationContext.SerializationPair.fromSerializer(
11            new GenericJackson2JsonRedisSerializer()
12        )
13    );

That keeps key storage simple while making values JSON-based.

Customize Specific Caches Differently

Sometimes one cache should use a different TTL or even a different serializer from another. For that, customize the cache manager rather than only the default configuration.

java
1import java.time.Duration;
2import org.springframework.boot.autoconfigure.cache.RedisCacheManagerBuilderCustomizer;
3import org.springframework.context.annotation.Bean;
4import org.springframework.data.redis.cache.RedisCacheConfiguration;
5
6@Bean
7RedisCacheManagerBuilderCustomizer redisCacheManagerBuilderCustomizer() {
8    RedisCacheConfiguration jsonConfig = RedisCacheConfiguration.defaultCacheConfig()
9        .entryTtl(Duration.ofMinutes(10))
10        .serializeValuesWith(
11            RedisSerializationContext.SerializationPair.fromSerializer(
12                new GenericJackson2JsonRedisSerializer()
13            )
14        );
15
16    return builder -> builder
17        .withCacheConfiguration("users", jsonConfig)
18        .withCacheConfiguration("products", jsonConfig.entryTtl(Duration.ofMinutes(30)));
19}

This gives you per-cache control without rewriting the whole cache infrastructure.

Match the Serializer to the Data Contract

Serializer choice is also a data-contract decision. If several services read the same Redis keys, they need compatible serialization formats. A Java-only binary serializer may be fine for one service's internal cache, but it is a poor fit if other systems need to inspect or share the values.

JSON is a common compromise because it is inspectable and broadly interoperable, though it is not always the most compact format.

Test Cache Compatibility Early

Whenever you change serializers, test both:

  • writing new cache entries
  • reading entries that may already exist

Serializer changes can break deserialization of old entries. In some deployments, the safest rollout is to change the serializer and clear the affected cache namespace at the same time.

That is especially important in production systems where old cached values may survive application restarts.

Common Pitfalls

The first pitfall is changing the serializer without considering existing cached entries. Old data may become unreadable and trigger runtime failures.

Another issue is configuring a serializer on RedisTemplate and assuming it automatically changes Spring's cache abstraction. Cache configuration and template configuration are related but not identical concerns.

Developers also switch away from JDK serialization without checking whether the cached object graph is actually JSON-friendly. Some types need explicit Jackson support or a simpler cached DTO shape.

Finally, keep key serialization simple unless you have a strong reason not to. String keys are usually the operationally easiest choice.

Summary

  • Change Spring Boot Redis cache serialization by customizing RedisCacheConfiguration.
  • A common choice is GenericJackson2JsonRedisSerializer for cache values.
  • Configure keys and values separately so each uses the most suitable format.
  • Use cache-manager customization for per-cache serializer or TTL differences.
  • Test serializer changes against existing cache contents before rolling them out broadly.

Course illustration
Course illustration

All Rights Reserved.