Sub topic 11
Configuring Redis for a shared cache
Caffeine keeps entries inside each JVM. If you run three copies of an application, each copy has its own cache. An update handled by one instance leaves stale entries in the other two. Redis fixes this by holding the cache in a separate server that every instance reads and writes. This chapter shows how to set that up in Spring Boot and what changes compared with a local cache.
This chapter assumes you have @Cacheable, @CachePut and @CacheEvict working with the products cache from earlier chapters. You also need a Redis server you can reach. A local one is enough, for example docker run -p 6379:6379 redis:7.
How the pieces fit
Your service code does not change when you move to Redis. Only the CacheManager behind the annotations changes. Boot builds a RedisCacheManager, which stores each entry as a key and a serialized value in Redis.
Every cache read is now a network call. A Redis hit usually takes about a millisecond, much slower than an in-process Caffeine hit. In return, all instances agree on what is cached.
Dependencies and connection
Add spring-boot-starter-cache and spring-boot-starter-data-redis. Point Boot at the server. These are the Boot 3 property names.
spring.data.redis.host=localhost
spring.data.redis.port=6379
# spring.data.redis.password=...
# spring.data.redis.ssl.enabled=true
spring.cache.type=redisSetting spring.cache.type=redis is optional when Redis is the only provider on the classpath. It makes the choice explicit and fails at startup if the provider is missing, which is easier to debug than a silent fallback to a different provider.
Configuring through properties
The properties from the spine cover the common cases.
spring.cache.redis.time-to-live=10m
spring.cache.redis.cache-null-values=false
spring.cache.redis.key-prefix=shop::
spring.cache.redis.use-key-prefix=true| Property | Effect |
|---|---|
| `time-to-live` | Redis expires each entry this long after it is written. With no value, entries never expire. |
| `cache-null-values` | When false, a `null` result cannot be stored. Spring raises an error if a `@Cacheable` method returns `null` and has no `unless` guard. |
| `key-prefix` | A string placed in front of every key. |
| `use-key-prefix` | When false, keys are stored without any prefix. |
The prefix is placed before the cache name, so a product with ID 1 is stored as shop::products::1. Different caches cannot collide on the same ID. Use a prefix per application when several applications share one Redis server. You can confirm the real key format with redis-cli --scan --pattern 'shop::*'.
The unless = "#result == null" guard in findById matters here. Without it, cache-null-values=false turns a "not found" result into an exception instead of a miss.
Serialization: the part that bites
Redis stores bytes, so Spring must serialize your values. The default is JDK serialization. That has two consequences.
- Cached classes must implement
java.io.Serializable. TheProductrecord from earlier fails at runtime with aSerializationExceptionunless you declarerecord Product(...) implements Serializable. - The stored bytes are tied to the class structure. A rolling deploy that changes
Productcan leave old entries that new instances cannot read.
JSON is the more common choice for a shared cache. You can read it with redis-cli, and it tolerates small class changes better. Define a RedisCacheConfiguration bean.
import java.time.Duration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
@Configuration
public class CacheConfig {
@Bean
RedisCacheConfiguration cacheConfiguration() {
return RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(10))
.disableCachingNullValues()
.prefixCacheNameWith("shop::")
.serializeValuesWith(RedisSerializationContext.SerializationPair
.fromSerializer(new GenericJackson2JsonRedisSerializer()));
}
}GenericJackson2JsonRedisSerializer writes a type name (@class) into each JSON document so it can rebuild the right class on read. Test a full write and read with your real types, especially records and classes with BigDecimal or date fields. A value that comes back as a LinkedHashMap causes a ClassCastException in the calling code. That means the type information was missing or the class cannot be rebuilt by Jackson. Because the type name is stored, renaming or moving a cached class also invalidates old entries.
Different expiry for each cache
A single TTL rarely fits every cache. Product data might live ten minutes, while search results should go stale faster. A RedisCacheManagerBuilderCustomizer adds per-cache settings on top of the default.
import java.time.Duration;
import org.springframework.boot.autoconfigure.cache.RedisCacheManagerBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
@Configuration
public class CacheTtlConfig {
@Bean
RedisCacheManagerBuilderCustomizer perCacheTtl(RedisCacheConfiguration base) {
return builder -> builder
.withCacheConfiguration("productSearch", base.entryTtl(Duration.ofMinutes(1)))
.withCacheConfiguration("reports", base.entryTtl(Duration.ofHours(1)));
}
}The customizer derives each configuration from base, so serializer, prefix and null handling carry over. Building each one from defaultCacheConfig() would silently bring back JDK serialization. In Boot 4 this interface moves to a different package, so check the import against your version.
When Redis is unavailable
A cache should speed things up, not become a new way for requests to fail. By default, a connection error from Redis propagates out of the @Cacheable method, and the request fails even though the database is healthy. A CacheErrorHandler lets you log the error and carry on as if the entry were missing.
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.Cache;
import org.springframework.cache.annotation.CachingConfigurer;
import org.springframework.cache.interceptor.CacheErrorHandler;
import org.springframework.cache.interceptor.SimpleCacheErrorHandler;
import org.springframework.context.annotation.Configuration;
@Configuration
public class CacheErrorConfig implements CachingConfigurer {
private static final Logger log = LoggerFactory.getLogger(CacheErrorConfig.class);
@Override
public CacheErrorHandler errorHandler() {
return new SimpleCacheErrorHandler() {
@Override
public void handleCacheGetError(RuntimeException e, Cache cache, Object key) {
log.warn("Cache read failed for {} key {}", cache.getName(), key, e);
}
};
}
}Only reads are forgiven here. Write and evict errors still throw, which is deliberate. If an evict fails silently, other instances keep serving stale data. Decide per operation whether a failure is acceptable.
Behavior to expect in a shared cache
- Keys must convert to strings.
RedisCacheturns the key into text with a conversion service. A custom key object needs a usefultoString()or a registered converter, or it fails. - Clearing all entries scans Redis.
@CacheEvict(allEntries = true)removes keys matching the cache's prefix. The default strategy uses theKEYScommand, which blocks Redis while it walks the whole keyspace. On a large database, build theRedisCacheWriterwithBatchStrategies.scan(...)instead. - The server has its own eviction. If Redis reaches
maxmemory, itsmaxmemory-policydecides what to drop. For a cache,allkeys-lruis a common setting. Do not rely on the cache for data that must never disappear. - Everyone shares the TTL. Entries expire for all instances at once, so a popular key can cause many instances to miss together. The
sync = trueoption from a later chapter limits that to one load per instance.
Exercise
You switch the products cache from Caffeine to Redis with JDK serialization. The service starts, but the first findById call fails with a SerializationException, and you also added a RedisCacheConfiguration bean with a 5-minute TTL while spring.cache.redis.time-to-live=10m is still in application.properties. What are the two problems, and what TTL do entries get?
Show answer
First, Product does not implement Serializable, which JDK serialization requires. Make the record implement Serializable, or switch the bean to a JSON serializer. Second, the properties and the bean conflict. Because a RedisCacheConfiguration bean exists, Boot ignores the spring.cache.redis.* properties, so the 10-minute property has no effect and entries get the bean's 5-minute TTL. Remove the property to avoid confusion.