Skip to content

Latest commit

 

History

History
132 lines (97 loc) · 4.68 KB

redis-cache.adoc

File metadata and controls

132 lines (97 loc) · 4.68 KB

Redis Cache

Note
Changed in 2.0

Spring Redis provides an implementation for the Spring cache abstraction through the org.springframework.data.redis.cache package. To use Redis as a backing implementation, add RedisCacheManager to your configuration, as follows:

@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
	return RedisCacheManager.create(connectionFactory);
}

RedisCacheManager behavior can be configured with RedisCacheManagerBuilder, letting you set the default RedisCacheConfiguration, transaction behavior, and predefined caches.

RedisCacheManager cm = RedisCacheManager.builder(connectionFactory)
	.cacheDefaults(defaultCacheConfig())
	.withInitialCacheConfigurations(singletonMap("predefined", defaultCacheConfig().disableCachingNullValues()))
	.transactionAware()
	.build();

As shown in the preceding example, RedisCacheManager allows definition of configurations on a per-cache basis.

The behavior of RedisCache created with RedisCacheManager is defined with RedisCacheConfiguration. The configuration lets you set key expiration times, prefixes, and RedisSerializer implementations for converting to and from the binary storage format, as shown in the following example:

RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
    .entryTtl(Duration.ofSeconds(1))
	.disableCachingNullValues();

RedisCacheManager defaults to a lock-free RedisCacheWriter for reading and writing binary values. Lock-free caching improves throughput. The lack of entry locking can lead to overlapping, non-atomic commands for the putIfAbsent and clean methods, as those require multiple commands to be sent to Redis. The locking counterpart prevents command overlap by setting an explicit lock key and checking against presence of this key, which leads to additional requests and potential command wait times.

Locking applies on the cache level, not per cache entry.

It is possible to opt in to the locking behavior as follows:

RedisCacheManager cm = RedisCacheManager.build(RedisCacheWriter.lockingRedisCacheWriter(connectionFactory))
	.cacheDefaults(defaultCacheConfig())
	...

By default, any key for a cache entry gets prefixed with the actual cache name followed by two colons. This behavior can be changed to a static as well as a computed prefix.

The following example shows how to set a static prefix:

// static key prefix
RedisCacheConfiguration.defaultCacheConfig().prefixKeysWith("( ͡° ᴥ ͡°)");

The following example shows how to set a computed prefix:

// computed key prefix
RedisCacheConfiguration.defaultCacheConfig().computePrefixWith(cacheName -> \_(ツ)_/¯" + cacheName);

The cache implementation defaults to use KEYS and DEL to clear the cache. KEYS can cause performance issues with large keyspaces. Therefore, the default RedisCacheWriter can be created with a BatchStrategy to switch to a SCAN-based batch strategy. The SCAN strategy requires a batch size to avoid excessive Redis command roundtrips:

RedisCacheManager cm = RedisCacheManager.build(RedisCacheWriter.nonLockingRedisCacheWriter(connectionFactory, BatchStrategies.scan(1000)))
	.cacheDefaults(defaultCacheConfig())
	...
Note
The KEYS batch strategy is fully supported using any driver and Redis operation mode (Standalone, Clustered). SCAN is fully supported when using the Lettuce driver. Jedis supports SCAN only in non-clustered modes.

The following table lists the default settings for RedisCacheManager:

Table 1. RedisCacheManager defaults
Setting Value

Cache Writer

Non-locking, KEYS batch strategy

Cache Configuration

RedisCacheConfiguration#defaultConfiguration

Initial Caches

None

Transaction Aware

No

The following table lists the default settings for RedisCacheConfiguration:

Table 2. RedisCacheConfiguration defaults
Key Expiration None

Cache null

Yes

Prefix Keys

Yes

Default Prefix

The actual cache name

Key Serializer

StringRedisSerializer

Value Serializer

JdkSerializationRedisSerializer

Conversion Service

DefaultFormattingConversionService with default cache key converters

Note

By default RedisCache, statistics are disabled. Use RedisCacheManagerBuilder.enableStatistics() to collect local hits and misses through RedisCache#getStatistics(), returning a snapshot of the collected data.