gpt4 book ai didi

node.js - EXPIRE Redis key (如果未修改)

转载 作者:IT王子 更新时间:2023-10-29 06:11:23 25 4
gpt4 key购买 nike

如果值在过去 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);
});
});
});

(抱歉回调金字塔)。

在我的系统上运行:

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

关于node.js - EXPIRE Redis key (如果未修改),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35195119/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com