如果未修改,则为EXPIRE Redis密钥

时间:2016-02-04 07:36:35

标签: node.js redis node-redis

如果在过去的x分钟内没有修改过值,是否可以直接使用EXPIRE redis键?

我怀疑这是可能的 - 但我想知道是否存在本机解决方案或具有非常少的逻辑和/或额外状态的东西。

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

1 个答案:

答案 0 :(得分:2)

你的假设是正确的,只是一个接一个地过期。

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

(对不起回调金字塔)。

在我的系统上运行:

[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秒的时间。

相关问题