Configuration
The RedisCacheConfiguration object is the entry point to configure a Redis cache and enable its features.
Key Function
Use keyFunction(KeyFunction function) to set the KeyFunction used to compute Redis keys.
Default is KeyFunction.SIMPLE which produces keys in the form <cache>:<key>.
Key Expiration
To enable entry time-to-live (TTL) use entryTtl(Duration duration) or entryTtl(TtlFunction function).
Default is TtlFunction.PERSISTENT which does not expire keys.
RedisCacheConfiguration config = RedisCacheConfiguration.defaultConfig()
.entryTtl(Duration.ofMinutes(10));
Redis Data Type
Use redisType(RedisType type) to change the type of data-structure backing the cache.
Possible values are HASH, STRING, and JSON.
Default is HASH.
RedisCacheConfiguration config = RedisCacheConfiguration.defaultConfig()
.redisType(RedisType.JSON);
Value Mappers
Each type has a corresponding value mapper which can be overridden:
HASH-
Set with
RedisCacheConfiguration.hashMapper(RedisHashMapper mapper). Defaults tocom.redis.cache.common.mapping.ObjectHashMapper. STRING-
Set with
RedisCacheConfiguration.stringMapper(RedisStringMapper mapper). Defaults tocom.redis.cache.common.mapping.JdkSerializationStringMapper. JSON-
Set with
RedisCacheConfiguration.jsonMapper(RedisStringMapper mapper). Defaults tocom.redis.cache.common.mapping.GenericJackson2JsonMapper.
Async Mode
Use async(boolean async) to enable asynchronous (non-blocking) cache operations.
When async mode is enabled (async(true)), write operations like put() and evict() return immediately without waiting for Redis to complete the operation.
This can significantly improve application throughput by reducing latency for cache write operations.
RedisCacheConfiguration config = RedisCacheConfiguration.defaultConfig()
.async(true);
Default is false (synchronous mode).
|
In async mode:
|
Async mode is particularly useful for:
-
High-throughput applications where cache write latency is a bottleneck
-
Scenarios where eventual consistency is acceptable
-
Applications that can tolerate brief delays in cache propagation
// Example: High-throughput cache configuration
RedisCacheConfiguration config = RedisCacheConfiguration.defaultConfig()
.async(true)
.entryTtl(Duration.ofMinutes(10))
.redisType(RedisType.JSON);
RedisCacheManager cacheManager = RedisCacheManager.builder(client)
.defaults(config)
.build();
Next Steps
-
Features - Learn about advanced features
-
WebFlux Support - Reactive programming with Spring WebFlux
-
Indexing and Querying - Enable search capabilities
-
Client-Side Caching - Add local caching