首页 > 解决方案 > 如何防止redis中的缓存覆盖到期时间

问题描述

我有一个save用 Redis 模板调用的通用方法:

redisTemplate.expire(cacheType.name(), redisPropertyConfiguration.getTimeToLive(), TimeUnit.MINUTES);

每次我调用Redis模板的这个方法过期覆盖过期时间,我想阻止过期时间并在过期时间结束时放置它

标签: springspring-bootredisspring-data

解决方案


这是预期的,因为expire(K key, long timeout, TimeUnit unit)EXPIRE Redis 命令的包装器)被记录为

为给定的密钥设置生存时间。

你问 :

 I wanna prevent the expiration time and put it if the expiration time end

如果您在过期时间之后检查密钥,则无法防止过期。

您可以做的是在已过期的情况下再次添加密钥。
在 Redis 中,该命令TTL fooKey返回密钥的剩余生存时间。
好消息:Spring Boot Redis 模板 API 也实现了:

public Long getExpire(K key)

在几秒钟内获得关键的时间。

所以你可以写这样的东西:

if (redisTemplate.getExpire(cacheType.name()) == -1L){
  // re-add the key-value
  redisTemplate.opsForValue.set(cacheType.name(), fooValue);
}

推荐阅读