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

将键 key 设置为指定的字符串值(String value)

Set key to hold the string value.

如果键 key 已经保存了一个值,将会被直接覆盖,且不管其原始值的类型。

If key already holds a value, it is overwritten, regardless of its type.

SET 命令执行成功时,任何之前针对键 key 设置的存在时间(Time to live)都将被直接丢弃。

Any previous time to live associated with the key is discarded on successful SET operation.
  • 2.6.12 开始,SET 新增以下选项以支持对其行为的修改:

    • EX seconds -- 以(Seconds)为单位,设置指定的过期时间(Expire time)
    • PX milliseconds -- 以毫秒(Seconds)为单位,设置指定的过期时间(Expire time)
    • NX -- 仅当目标键不存在时才进行设置操作
    • XX -- 仅当目标键存在时才进行设置操作

    EX seconds -- Set the specified expire time, in seconds.
    PX milliseconds -- Set the specified expire time, in milliseconds.
    NX -- Only set the key if it does not already exist.
    XX -- Only set the key if it already exist.

    注意 因为 SET 命令可以通过设置不同选项来替代 SETNXSETEXPSETEX,在 Redis 的未来版本中上述三条命令可能会被不推荐使用(Deprecated)且最终被删除。

    Note: Since the SET command options can replace SETNX, SETEX, PSETEX, it is possible that in future versions of Redis these three commands will be deprecated and finally removed.

  • 如果 SET 命令正常执行,则返回 OK,否则返回(nil)

    OK if SET was executed correctly. Null reply: a Null Bulk Reply is returned if the SET operation was not performed becase the user specified the NX or XX option but the condition was not met.
  • redis> SET mykey "Hello"
    OK
    redis> GET mykey
    "Hello"
    redis> SET mykey "classfoo.com" NX
    (nil)
  • 命令 SET resource-name anystring NX EX max-lock-time 是一种用 Redis 来实现锁机制的简单方法。

    The command SET resource-name anystring NX EX max-lock-time is a simple way to implement a locking system with Redis.
    A client can acquire the lock if the above command returns OK (or retry after some time if the command returns Nil), and remove the lock just using DEL.
    The lock will be auto-released after the expire time is reached.
    It is possible to make this system more robust modifying the unlock schema as follows:
    1. Instead of setting a fixed string, set a non-guessable large random string, called token.
    2. Instead of releasing the lock with DEL, send a script that only removes the key if the value matches.
    This avoids that a client will try to release the lock after the expire time deleting the key created by another client that acquired the lock later.

    在实现解锁脚本(Unlock script)时,一般会与以下例子类似:

    if redis.call("get",KEYS[1]) == ARGV[1]
    then
        return redis.call("del",KEYS[1])
    else
        return 0
    end
  • 版本支持

    1.0.0+ 特殊选项 2.6.12+

    时间复杂度(Time complexity)

    O(1)