Sub topic 11
Configuring Redis for a shared cache
This chapter assumes you can already use @Cacheable, @CachePut and @CacheEvict, and that you can run a Redis server locally (for example with Docker). It covers moving the cache from application memory into Redis.
Why Redis
A Caffeine cache lives inside one JVM. If you run three instances of your service, each has its own copy. An update handled by instance A leaves stale entries on B and C. Redis is a separate server that all instances talk to, so they share one cache and one eviction. The cost is a network call on every lookup and the need to serialize values.
The annotations in your code do not change. Only the CacheManager behind them does.
Configuration with properties
Add spring-boot-starter-cache and spring-boot-starter-data-redis, then set:
spring.cache.type=redis
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=trueBoot then creates a RedisCacheManager with these defaults:
time-to-livemakes every entry expire 10 minutes after it is written. Without it, entries never expire.cache-null-values=falserefuses to storenull. It pairs well withunless = "#result == null".key-prefixputs a namespace in front of the cache name in each Redis key. This keeps several applications on one Redis server from colliding.
By default Boot connects to localhost:6379. Use spring.data.redis.host and spring.data.redis.port to change that.
Configuration with a bean
Properties apply one policy to all caches. For control over serialization, define a RedisCacheConfiguration bean:
@Configuration
public class CacheConfig {
@Bean
RedisCacheConfiguration cacheConfiguration() {
return RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(10))
.disableCachingNullValues()
.serializeValuesWith(RedisSerializationContext.SerializationPair
.fromSerializer(new GenericJackson2JsonRedisSerializer()));
}
}Boot detects this bean and uses it as the default configuration for the RedisCacheManager. The bean takes precedence over the spring.cache.redis.* settings, so define the TTL and the other options in one place only.
Things to watch for
- Class changes during deployments. Entries written by an old version may fail to deserialize in a new one. A short TTL limits the damage. Changing the key prefix gives the new version a fresh namespace.
- Network failures. If Redis is down, cached methods throw by default instead of falling back to the real method. Decide whether that is acceptable, or register a custom
CacheErrorHandler. - Size. Redis has no per-cache size limit like Caffeine's
maximumSize. Control memory with TTLs and the server'smaxmemorypolicy. - Inspecting data. Run
redis-cli KEYS 'shop::*'on a development instance to see the keys Spring wrote. AvoidKEYSon production servers.
Exercise
You deploy a second instance of your service with Caffeine as the cache. After delete(5L) on instance A, instance B still returns product 5 from its cache. What change fixes this, and which two Redis settings would you add so that entries do not live forever and do not collide with other applications?
Show answer
Switch the provider to Redis with spring.cache.type=redis, so both instances share one cache and the eviction applies to both. Add a TTL, for example spring.cache.redis.time-to-live=10m, so entries expire. Add a key prefix, for example spring.cache.redis.key-prefix=shop::, to namespace the keys. Cached classes must also be serializable, either by implementing Serializable or by configuring a JSON serializer.