首页 > 解决方案 > 使用spring-boot-starter-data-redis时,如何设置驱逐策略?LFU或LRU等?

问题描述

当通过spring boot()将redis用作缓存技术时<artifactId>spring-boot-starter-data-redis</artifactId>,我看到文件中很少可以设置像TTL这样的属性application.properties。前任:

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

以及来自 -附录 A. 常见应用程序属性的更多片段

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.

但我无法弄清楚如何设置缓存驱逐策略,例如 - 最不常用或最近最近使用等。
我必须如何以及在哪里提供此配置详细信息?

标签: springspring-bootredisspring-data-redis

解决方案


Redis缓存文档指出:

可以使用 redis.conf 文件设置配置指令,或者稍后在运行时使用 CONFIG SET 命令。

Redis配置文档指出:

maxmemory 2mb
maxmemory-policy allkeys-lru

结合两者,改变驱逐策略的命令是:

CONFIG SET maxmemory-policy allkeys-lfu

使用 Spring Data Redis:

如果使用非反应式 Redis 连接:

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

如果使用反应式 Redis 连接:

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

推荐阅读