Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/redis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js Redis到期并递增_Node.js_Redis_Node Redis - Fatal编程技术网

Node.js Redis到期并递增

Node.js Redis到期并递增,node.js,redis,node-redis,Node.js,Redis,Node Redis,我有一个场景,我想用redis实现一个缓存机制。进一步详述 首先,我使用client.get()检查特定键,如果该值不存在。我需要调用一个web服务,它返回一个值并存储为键的子项。然后我使用client.set()将该键设置到redis中。现在,如果此密钥已设置超过24小时,则它需要过期,我如何才能做到这一点 下面是redis中键值的示例 parentValue:{ child1:{ serviceVal: "serviceVal", counter: 0

我有一个场景,我想用redis实现一个缓存机制。进一步详述

首先,我使用client.get()检查特定键,如果该值不存在。我需要调用一个web服务,它返回一个值并存储为键的子项。然后我使用client.set()将该键设置到redis中。现在,如果此密钥已设置超过24小时,则它需要过期,我如何才能做到这一点

下面是redis中键值的示例

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

    child2:{...},
    child3:{...}
    .... 
}
现在,当执行初始的client.get()时,如果该值存在且该特定键尚未过期,则执行类似操作。我想增加对象中的计数器,并在redis中更新此特定键。我如何才能做到这一点?

选项是最简单的解决方案。请参阅我正在处理的模块的示例

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

但对于递增和过期,最好使用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
然后,您只需调用带有键、到期时间和增量的脚本