如果在最近的x分钟内未修改该值,是否有一种直接的方法来使redis键失效?

我怀疑这是否可能-但我想知道是否存在本机解决方案或某些逻辑和/或额外状态很少的解决方案。

现在,此行为可能已经存在-我在一个键上调用EXPIRE。然后,如果我在该键上调用SET,则可以再次调用EXPIRE,并且该键将使用新值而不是旧值EXPIRE?

最佳答案

您的假设是正确的,只是彼此之间会过期。

EXPIRE不会累积或重置或进行任何操作,它只是将计时器设置为新值。

示例(不进行冗长的错误处理):

'use strict';

let client = require('redis').createClient()
const KEY = 'my:key';
const TTL = 10;
let value = 'some-value';

client.on('ready', function() {

  console.log('Setting key...')
  client.set(KEY, value, function() {

    console.log('Setting expire on the key...');
    client.expire(KEY, TTL, function() {

      console.log('Waiting 6 sec before checking expire time...');
      // Check in 6 seconds, ttl should be around 6
      setTimeout(function() {

        client.ttl(KEY, function(err, expiryTime) {

          console.log('expiryTime:', expiryTime); // "expiryTime: 6" on my system
          // expire again to show it does not stack, it only resets the expire value

          console.log('Expiring key again...');
          client.expire(KEY, TTL, function() {

            // again wait for 3 sec
            console.log('Waiting 3 more sec before checking expire time...');
            setTimeout(function() {

              client.ttl(KEY, function(err, expiryTime) {

                console.log('New expiryTime:', expiryTime); // 7
                process.exit();
              })
            }, 3000);
          });
        });
      }, 6000);
    });
  });
});

(很抱歉回调piramid)。

在我的系统上运行:
[zlatko@desktop-mint ~/tmp]$ node test.js
Setting key...
Setting expire on the key...
Waiting 6 sec before checking expire time...
expiryTime: 4
Expiring key again...
Waiting 3 more sec before checking expire time...
New expiryTime: 7
[zlatko@desktop-mint ~/tmp]$

如您所见,我们将到期时间设置为10秒。 6秒后,显然剩下的时间是4秒。

如果那时我们还有4秒钟的时间,将到期时间再次设置为10,我们只需从10开始。
在此之后的3秒,我们仍然可以再使用7秒。

08-27 23:01