2020-02-07

Spring Redis Caching

Redis

If Redis is available and configured, a RedisCacheManager is auto-configured. It is possible to create
additional caches on startup by setting the configprop:spring.cache.cache-names[] property and
cache defaults can be configured by using spring.cache.redis.* properties. For instance, the
following configuration creates cache1 and cache2 caches with a time to live of 10 minutes:

spring.cache.cache-names=cache1,cache2
spring.cache.redis.time-to-live=600000

By default, a key prefix is added so that, if two separate caches use the same key,
Redis does not have overlapping keys and cannot return invalid values. We
strongly recommend keeping this setting enabled if you create your own
RedisCacheManager.

You can take full control of the default configuration by adding a
RedisCacheConfiguration @Bean of your own. This can be useful if you’re looking for
customizing the default serialization strategy.

If you need more control over the configuration, consider registering a
RedisCacheManagerBuilderCustomizer bean. The following example shows a customizer that
configures a specific time to live for cache1 and cache2:

@Bean
public RedisCacheManagerBuilderCustomizer myRedisCacheManagerBuilderCustomizer() {
return (builder) -> builder
.withCacheConfiguration("cache1",
RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofSeconds(10)))
.withCacheConfiguration("cache2",
RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofMinutes(1)));
}

No comments:

Post a Comment