问题描述
我正在使用 spring 缓存抽象注释来将缓存应用于我的服务方法.
I am spring caching abstraction annotations to apply caching to my service methods.
由于我使用 Redis 作为缓存存储,我想使用在特定时间使缓存过期的选项,因为 Redis 支持该选项.redis中的expireat命令可以用来设置以后的过期时间.
Since I am using Redis as the cache store, I want to use the option of expiring cache at a specific time, since that is supported by Redis. expireat command in redis can be used to set expire time at a future time.
我不确定如何在使用 RedisCache 时对属于我的缓存的键执行此操作.
I am not sure how I can do that for the keys which are part of my cache when using RedisCache.
我尝试通过创建它的 bean 来自定义 RedisCacheManager.
I tried to customize RedisCacheManager by creating a bean of it.
我看到有一个暴露的 getNativeCache() 方法.但我没有找到任何方法来使用它来设置 expireat 的值.
I see there is a getNativeCache() method exposed. but I did not find any way to set value for expireat using it.
如果有办法自定义 RedisCacheManager 以便特定缓存的所有键使用相同的时间作为到期,请告诉我.
If there is a way to customize RedisCacheManager so that all keys of a specifc cache use the same time as expiry, please let me know.
推荐答案
@Bean (name="cacheManager")
public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
RedisCacheConfiguration conf_ready_info = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMillis(50000));
RedisCacheConfiguration conf_base_info = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMillis(60000));
Map<String, RedisCacheConfiguration> cacheConfigurations = new HashMap<String, RedisCacheConfiguration>();
cacheConfigurations.put("base_info", conf_base_info);
cacheConfigurations.put("ready_info", conf_ready_info);
return RedisCacheManager.RedisCacheManagerBuilder.fromConnectionFactory(connectionFactory)
.withInitialCacheConfigurations(cacheConfigurations).build();
}
@Cacheable(value = "ready_info", key = "#aid")
public String findByAid(String aid) throws Exception {
String readyInfo = "";
return readyInfo;
}
这篇关于将 Spring 缓存与 Redis 一起使用时,在特定时间设置过期键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!