redis 中是否有命令可以为键设置默认值(如果键不存在)?
例如,如果get hello返回,(nil)我想将其默认为world. 但是如果键hello已经存在,我想返回这个值。
您可以使用 Lua 脚本来实现:
local value = redis.call("GET", KEYS[1])
if (not value) then
redis.call("SET", KEYS[1], ARGV[1])
return ARGV[1]
end
return value
Run Code Online (Sandbox Code Playgroud)
将其另存为script.lua并像这样调用它:
$ redis-cli eval "$(cat script.lua") 1 myKey defaultValue
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4726 次 |
| 最近记录: |