本文内容为 http://redis.io/commands/msetnx 的翻译、注解、例子扩充及其它修改。感谢 Redis 作者 Antirez 为开源社区作出的贡献,本文保证最新、最准、最全以表示对其的敬意。欢迎留言纠错、提示更新或支持。
MSETNX key value [key value ...]

将给定的所有键设置为对应的值。

Sets the given keys to their respective values.

如果被操作键已经存在,哪怕只有一个,都将终止所有操作。

MSETNX will not perform any operation at all even if just a single key already exists.

因存在该语义(Semantic)MSETNX 命令可以用于以设置多个键的形式设置某个唯一逻辑对象(Unique logic object)的不同字段,同时保证要么所有字段被设置,要么没有一个字段被设置。

Because of this semantic MSETNX can be used in order to set different keys representing different fields of an unique logic object in a way that ensures that either all the fields or none at all are set.

MSENX 命令是原子的(Atomic),因此所有给定键能够被一次性同时设置。对于客户端(程序)来说,不可能出现一部份键被更新,而还有一部份键未被更新的情况。

MSETNX is atomic, so all given keys are set at once. It is not possible for clients to see that some of the keys were updated while others are unchanged.
    • 返回 1,如果所有键被设置。
    • 返回 0,如果无任何键被设置(至少有一个键已经存在)。
    • 1 if the all the keys were set.
    • 0 if no key was set (at least one key already existed).
  • redis> MSETNX key1 "Hello" key2 "there"
    (integer) 1
    redis> MSETNX key2 "there" key3 "world"
    (integer) 0
    redis> MGET key1 key2 key3
    1) "Hello"
    2) "there"
    3) (nil)
  • 版本支持

    1.0.1+

    时间复杂度(Time complexity)

    O(N)N 为将要设置值的键的个数。

    O(N) where N is the number of keys to set.