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

将键 key 的值设置为值 value 并返回旧值,整个操作是原子的(Atomical)

Atomically sets key to value and returns the old value stored at key.

如果键 key 已经存在,但对应的值非字符串类型,则返回一个错误。

Returns an error when key exists but does not hold a string value.
  • 返回命令执行前存储在键 key 中的旧值。

    如果键 key 不存在,则返回 nil

    the old value stored at key, or nil when key did not exist.
  • redis> SET mykey "Hello"
    OK
    redis> GETSET mykey "World"
    "Hello"
    redis> GET mykey
    "World"
  • GETSET 命令可以与 INCR 命令一起使用来实现原子重置(Atomic reset)功能。

    GETSET can be used together with INCR for counting with atomic reset. 

    例子:

    For example: a process may call INCR against the key mycounter every time some event occurs, but from time to time we need to get the value of the counter and reset it to zero atomically. This can be done using GETSET mycounter "0":
    redis> INCR mycounter
    (integer) 1
    redis> GETSET mycounter "0"
    "1"
    redis> GET mycounter
    "0"
  • 版本支持

    1.0.0+

    时间复杂度(Time complexity)

    O(1)