仅当Redis存在密钥时如何执行HSET? [英] How to do HSET only if key exists with Redis?

查看:57
本文介绍了仅当Redis存在密钥时如何执行HSET?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想运行 HSET 命令,但前提是密钥存在.与 HSETNX 类似,除了 exists 而不是 notexists

I want to run a HSET command but only if the key exists. Similar to HSETNX except exists instead of not exists

我已经读过有关可能使用 WATCH 或其他东西的信息,但到目前为止我无法真正弄清楚.我很感激朝着正确的方向轻推.我唯一看到的是这个,但我不明白这是如何工作的,因为这些甚至不是有效的 redis 命令.

I've read about maybe using WATCH or something but so far I can't really figure it out. I would appreciate a nudge in the right direction. The only thing I see is this but I don't see how this works considering these aren't even valid redis commands.

HSET,如果键存在

此外,在阅读了有关我关注的 WATCH 之后,因为如果另一个请求出现,我不想中止交易.

Also, after reading about WATCH that concerns me because I don't want to abort the transaction if another request comes it.

我基本上是在尝试 HGETALL,然后立即为 HSET 发出第二个命令,说它已被读取一次.

I'm basically trying to HGETALL and immediately after issue a second command for HSET, saying that it has been read a single time.

在那之后,我希望所有后续请求都知道它已经被读取了.

After that, I want all subsequent requests to know that it's already been read.

问题是,当我在一个不存在的键上调用 HSET 时,而不是仅仅失败,它会在 redis 数据库中创建一个我不想要的新条目.我只希望它在存在时更新记录,而不必先检查它是否存在

The problem is, when I call HSET on a key that doesn't exist, instead of just failing it creates a new entry in the redis database, which I don't want. I only want it to update records if it exists without having to check if it exists first

据此,该方法对于高争用无论如何都不起作用(会有很多对密钥的请求)

According to this, that method won't work anyway for high contention (there will be lots of requests to the key)

https://github.com/antirez/redis/issues/441

它说我可以以某种方式使用脚本,但我不确定

It says I could use scripting somehow but I'm not sure

推荐答案

是的.您可以通过运行 EVAL 命令在 Redis 中执行 lua 脚本.EVAL 之后的所有命令都会被阻塞,直到 EVAL 完成,因为 Redis 是一个单线程服务器.

Yes. You can execute a lua script in Redis by running EVAL command. All the commands after the EVAL will be blocked until the EVAL has completed, since Redis is a single-threaded server.

文档说:

EVAL 和 EVALSHA 用于使用 Redis 2.6.0 版本开始内置的 Lua 解释器来评估脚本.

EVAL and EVALSHA are used to evaluate scripts using the Lua interpreter built into Redis starting from version 2.6.0.

所以,很容易实现一个简单的HSETX命令,运行下面的lua脚本即可:<代码>eval "if redis.call('exists',KEYS[1]) == 1 then redis.call('hset', KEYS[1], ARGV[1], 0) end" 1 test_key test_field

So, it's easy to implement a simple HSETX command,just run the lua script below: eval "if redis.call('exists',KEYS[1]) == 1 then redis.call('hset', KEYS[1], ARGV[1], 0) end" 1 test_key test_field

这篇关于仅当Redis存在密钥时如何执行HSET?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆