When using spring-boot-starter-data-redis, how to set the eviction policy? LFU or LRU etc?

Viewed 1436

When redis is used as a caching technology through spring boot (<artifactId>spring-boot-starter-data-redis</artifactId>), i see few properties like TTL can be set in the application.properties file. ex:

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

and few more snippets from - Appendix A. Common application properties

spring.redis.database=0 # Database index used by the connection factory.
spring.redis.url= # Connection URL. Overrides host, port, and password. User is ignored. Example: redis://user:password@example.com:6379
spring.redis.host=localhost # Redis server host.

But I am not able to figure out how to set the cache eviction policy like - Least Frequently Used or Last Recently Used etc.
How and where do I have to provide this config details ??

1 Answers

Redis cache documentation states:

It is possible to set the configuration directive using the redis.conf file, or later using the CONFIG SET command at runtime.

Redis configuration documentation states:

maxmemory 2mb
maxmemory-policy allkeys-lru

Combining the two, the command to change the eviction policy is:

CONFIG SET maxmemory-policy allkeys-lfu

Using Spring Data Redis:

If using non-reactive Redis connection:

RedisConnection conn = null;
try {
    conn = connectionFactory.getConnection();
    conn.setConfig("maxmemory-policy", "allkeys-lfu");
} finally {
    if (conn != null) {
        conn.close();
    }
}

If using reactive Redis connection:

ReactiveRedisConnection conn = connectionFactory.getReactiveConnection();
        conn
                .serverCommands()
                .setConfig("maxmemory-policy", "allkeys-lfu")
                .filter(status -> status.equals("OK"))
                .doFinally(unused -> conn.close())
                .block(Duration.ofSeconds(5L));
Related