Redis - 如何每日过期密钥

问题描述 投票:0回答:4

我知道Redis中的EXPIREAT是用来指定key什么时候过期的。但我的问题是它需要一个绝对的 UNIX 时间戳。如果我希望密钥在一天结束时过期,我很难思考应该将什么设置为参数。

这就是我设置密钥的方式:

client.set(key, body);

所以要将过期时间设置为:

client.expireat(key, ???);

有什么想法吗?我将其与 nodejs 和 sailsjs 一起使用 谢谢!

node.js unix redis timestamp sails.js
4个回答
51
投票

如果你想在24小时后过期

client.expireat(key, parseInt((+new Date)/1000) + 86400);

或者如果您希望它在今天结束时正好过期,您可以在 .setHours

 对象上使用 
new Date()
 来获取当天结束的时间,然后使用它。

var todayEnd = new Date().setHours(23, 59, 59, 999);
client.expireat(key, parseInt(todayEnd/1000));

34
投票

由于SETNX、SETEX、PSETEX将在下一个版本中被弃用,正确的方法是:

client.set(key, value, 'EX', 60 * 60 * 24, callback);

有关上述内容的详细讨论,请参见此处


18
投票

您可以一起设置价值和到期时间。

  //here key will expire after 24 hours
  client.setex(key, 24*60*60, value, function(err, result) {
    //check for success/failure here
  });

 //here key will expire at end of the day
  client.setex(key, parseInt((new Date().setHours(23, 59, 59, 999)-new Date())/1000), value, function(err, result) {
    //check for success/failure here
  });

0
投票

对于新版本,你可以使用 set 和 expire like

await client.set(key , value, {EX: 60*60*24})
© www.soinside.com 2019 - 2024. All rights reserved.