问题描述
当通过弹簧引导(<artifactId>spring-boot-starter-data-redis</artifactId>
)将redis用作缓存技术时,我发现application.properties
文件中几乎没有可以设置类似TTL的属性。
例如:
spring.cache.cache-names=cache1,cache2
spring.cache.redis.time-to-live=600000
和-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.
但是我无法弄清楚如何设置缓存逐出策略,例如-最少使用或最近使用等。
我必须如何以及在何处提供此配置详细信息?
解决方法
Redis cache documentation 声明:
可以使用 redis.conf 设置配置指令 文件,或稍后在运行时使用 CONFIG SET 命令。
Redis configuration documentation 声明:
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));