【问题标题】:Redis expire and incrementRedis 过期和递增
【发布时间】:2016-08-22 10:18:55
【问题描述】:

我有一个场景,我想用 redis 实现一个缓存机制。深入了解

首先,我使用 client.get() 检查特定键,如果该值不存在。我需要调用一个 Web 服务,该服务返回一个值并存储为键的子项。然后我使用 client.set() 将此密钥设置为 redis。现在这个key如果设置超过24小时就要过期了,怎么办?

这是一个键值在 redis 中的示例

parentValue:{
    child1:{
        serviceVal: "serviceVal",
        counter: 0
    },

    child2:{...},
    child3:{...}
    .... 
}

现在类似地,当执行初始 client.get() 时,如果值存在且此特定密钥尚未过期。我想增加对象中的 counter 并在 redis 中更新这个特定的键。我该怎么做?

【问题讨论】:

    标签: node.js redis node-redis


    【解决方案1】:

    SET with NX and EX 选项是您最简单的解决方案。查看我正在开发的模块的示例here

    EX 接受秒数,因此您需要 86400 秒数为 24 小时。

    但对于递增和过期,您可能最好使用 redis lua 脚本,例如:

    --[[
      key 1 -> key name
      arg 1 -> expires in seconds
      arg 2 -> incr by value
    ]]
    
    -- Key exists so increment it
    if redis.call('exists',KEYS[1]) > 0 then
      redis.call('incrby',KEYS[1],tonumber(ARGV[2]))
      return 0
    else
      -- key doesn't exist so create with an expiry and the incr amount
      redis.call('setex',KEYS[1],tonumber(ARGV[1]),tonumber(ARGV[2]))
      return 1
    end
    

    然后您只需使用密钥、到期时间和增量多少来调用脚本。

    【讨论】:

      猜你喜欢
      • 2020-04-23
      • 2017-10-09
      • 2020-08-20
      • 1970-01-01
      • 2015-05-01
      • 2013-05-20
      • 2013-09-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多