仅当尚未设置时才设置原子 [英] Atomic set only if not already set

查看:49
本文介绍了仅当尚未设置时才设置原子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法只在Redis中没有设置时才做原子集?

具体来说,我正在创建一个像myapp:user:user_email"这样的用户,如果user_email"已经被占用,我希望Redis给我一个错误,而不是默默地替换旧值.类似于声明,而不是替换.

解决方案

参见 SETNX

<块引用><块引用>

如果键不存在,则设置键以保存字符串值.在这种情况下,它等于 SET.当 key 已经持有一个值时,不执行任何操作.SETNX 是SET if Not e Xists"的缩写.

您可以检查返回值.如果为 0,则表示该键未设置,表示该键已存在.

Is there any way to do an atomic set only if not already set in Redis?

Specifically, I'm creating a user like "myapp:user:user_email" and want Redis to give me back an error if "user_email" is already taken, instead of silently replacing the old value. Something like declare, not replace.

解决方案

See SETNX

Set key to hold string value if key does not exist. In that case, it is equal to SET. When key already holds a value, no operation is performed. SETNX is short for "SET if N ot e X ists".

You can check the return value. If it is 0, the key was not set, implying it already existed.

这篇关于仅当尚未设置时才设置原子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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