【问题标题】:How to set expiration time for hmset in node redis?如何在节点redis中设置hmset的过期时间?
【发布时间】:2019-05-24 15:53:42
【问题描述】:

我曾经使用client.setex(key, 900, value) 来存储单个键值。
但是,我想存储一个有过期时间的对象。
我想出了函数hmset,但是我不知道如何设置过期时间。
我想用它来存储对话中当前聊天的上下文和文本。
请帮忙

【问题讨论】:

    标签: node.js redis chat chatbot node-redis


    【解决方案1】:

    要使哈希(或任何其他 Redis 键)过期,请调用 EXPIRE 命令。在你的情况下:

    client.hmset(key, ...
    client.expire(key, 9000)
    

    【讨论】:

    • 问题是那些是 2 个命令,意味着整个操作不是原子的。如果由于某种原因,client.expire() 不会被处理,那么您最终会得到一个永不过期的记录。如果 Redis 有一个命令来同时设置哈希和定义其过期时间,那就太好了。
    • 是的,但是您可以使用MULTI/EXEC 块或 Lua 脚本来确保原子性,而不是使用专用命令。
    • @StasKorzovsky 我需要通过 hmset 为我的密钥集设置过期时间。你能帮我怎么做吗?上面的方法向我显示键的 TTL 为 -1。
    【解决方案2】:

    由于 hmset 已弃用 (see this),您可以将 hsetexpire 一起使用 pipeline

    pipe = client.pipeline()
    pipe.hset(key, mapping=your_object).expire(duration_in_sec).execute()
    
    # for example:
    pipe.hset(key, mapping={'a': 1, 'b': 2}).expire(900).execute()
    

    注意Pipeline does not ensure atomicity.

    【讨论】:

      【解决方案3】:

      确保在 key 之后设置过期的好方法是将进程包装在 ES6 异步函数中:

      async function (keyString, token, ttl) {
              return new Promise(function(resolve, reject) {
                  redisClient.hmset("auth", keyString, token, function(error,result) {
                      if (error) {
                          reject(error);
                      } else {
                          redisClient.expire(keyString, ttl)
                          resolve(result);
                      }
                  });
              });
          }
      

      【讨论】:

      • 它不能帮助你确保原子性,这在上面已经讨论过了。
      猜你喜欢
      • 1970-01-01
      • 2016-05-15
      • 1970-01-01
      • 1970-01-01
      • 2013-10-02
      • 2020-05-12
      • 2018-12-06
      • 1970-01-01
      • 2019-07-25
      相关资源
      最近更新 更多