如何防止redis中的缓存覆盖到期时间

dfddblmv  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(300)

我有一个通用方法叫做 save 使用redis模板:

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

每次我调用redis模板expire的这个方法覆盖过期时间,我想阻止过期时间,如果过期时间结束就放它

b5buobof

b5buobof1#

这是因为 expire(K key, long timeout, TimeUnit unit) (expire redis命令的 Package 器)记录为
为给定的密钥设置生存时间。
你问:

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);
}

相关问题