Redis - 如何每天使密钥过期

Redis - How to expire key daily

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

这是我设置密钥的方式:

client.set(key, body);

因此要将过期时间设置为:

client.expireat(key, ???);

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

如果你想在 24 小时后过期

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

或者如果您希望它恰好在今天结束时过期,您可以在 new Date() 对象上使用 .setHours 来获取当天结束的时间,然后使用它。

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

您可以同时设置价值和有效期。

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

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

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

有关上述内容的详细讨论,请参阅 here