node.js Redis - 如何每天使密钥过期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30565571/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 18:49:16  来源:igfitidea点击:

Redis - How to expire key daily

node.jsunixredistimestampsails.js

提问by bless1204

I know that EXPIREAT in Redis is used to specify when a key will expire. My problem though is that it takes an absolute UNIX timestamp. I'm finding a hard time thinking about what I should set as an argument if I want the key to expire at the end of the day.

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

This is how I set my key:

这是我设置密钥的方式:

client.set(key, body);

client.set(key, body);

So to set the expire at:

因此,将到期时间设置为:

client.expireat(key, ???);

client.expireat(key, ???);

Any ideas? I'm using this with nodejs and sailsjs Thanks!

有任何想法吗?我正在将它与 nodejs 和 Sailsjs 一起使用 谢谢!

回答by laggingreflex

If you want to expire it 24 hrs later

如果您想在 24 小时后到期

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

Or if you want it to expire exactly at the end of today, you can use .setHourson a new Date()object to get the time at the end of the day, and use that.

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

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

回答by loretoparisi

Since SETNX, SETEX, PSETEXare going to be deprecated in the next releases, the correct way is:

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

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

See herefor a detailed discussion on the above.

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

回答by Praveena

You can set value and expiry together.

您可以同时设置 value 和 expiry。

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