【问题标题】:EXPIRE Redis key if not modified如果未修改,则 EXPIRE Redis 密钥
【发布时间】:2016-02-04 07:36:35
【问题描述】:

如果值在过去 x 分钟内没有被修改,是否有一种直接的方法来 EXPIRE 一个 redis 键?

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

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

【问题讨论】:

  • 我有同样的情况,所以我按照你说的做了。每当我访问密钥时,我都会用一个新值来延长它的到期时间。就是这样。

标签: node.js redis node-redis


【解决方案1】:

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

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 秒。

【讨论】:

  • 谢谢,来自 Redis 文档“只有删除或覆盖密钥内容的命令才能清除超时,包括 DEL、SET、GETSET 和所有 *STORE 命令......”所以看起来我需要小心在调用 SET 后调用 EXPIRE,而不是相反。但是,如果 SET 总是清除超时,那么文档并没有说清楚......我想我需要知道 SET 是否总是清除超时。
  • 是的,但您也可以使用 setex 自动设置和过期密钥。
  • 另外,SET 不会清除超时。只需将新值添加到之前可能存在的可选超时的键中。
猜你喜欢
  • 2021-09-11
  • 1970-01-01
  • 1970-01-01
  • 2011-01-17
  • 2020-05-01
  • 2021-11-03
  • 1970-01-01
  • 1970-01-01
  • 2011-03-27
相关资源
最近更新 更多