Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/spring-boot/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring 如何在redis中防止缓存覆盖到期时间_Spring_Spring Boot_Redis_Spring Data - Fatal编程技术网

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

Spring 如何在redis中防止缓存覆盖到期时间,spring,spring-boot,redis,spring-data,Spring,Spring Boot,Redis,Spring Data,我使用Redis模板有一个名为save的通用方法: redisTemplate.expire(cacheType.name(), redisPropertyConfiguration.getTimeToLive(), TimeUnit.MINUTES); 每次我调用这个方法时,Redis模板的expire会覆盖过期时间,我想防止过期时间,并在过期时间结束时使用它,因为(Redis命令的包装器)被记录为 设置给定密钥的生存时间 你问: 如果在过期时间之后检查密钥,则无法阻止过期 如果密钥已过期,

我使用Redis模板有一个名为
save
的通用方法:

redisTemplate.expire(cacheType.name(), redisPropertyConfiguration.getTimeToLive(), TimeUnit.MINUTES);
每次我调用这个方法时,Redis模板的expire会覆盖过期时间,我想防止过期时间,并在过期时间结束时使用它,因为(Redis命令的包装器)被记录为

设置给定密钥的生存时间

你问:

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

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

以秒为单位获取密钥的生存时间

所以你可以这样写:

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

redisTemplate.getExpire(cacheType.name())始终返回(-1)如果
getExpire()
返回负数,则它将表示密钥设置为“永不过期”或密钥不再退出。如果在过期时间之后检查密钥,则无法阻止过期。因此,要解决您的问题,您应该添加第二个检查,以便在缓存密钥过期时重新创建缓存密钥。
if (redisTemplate.getExpire(cacheType.name()) == -1L){
  // re-add the key-value
  redisTemplate.opsForValue.set(cacheType.name(), fooValue);
}