SET key value [EX seconds] [PX milliseconds] [NX|XX]
可用版本: >= 1.0.0時間復雜度: O(1)
將字符串值 value
關聯到 key
。
如果 key
已經持有其他值, SET
就覆寫舊值, 無視類型。
當 SET
命令對一個帶有生存時間(TTL)的鍵進行設置之后, 該鍵原有的 TTL 將被清除。
可選參數
從 Redis 2.6.12 版本開始, SET
命令的行為可以通過一系列參數來修改:
EX seconds
: 將鍵的過期時間設置為seconds
秒。 執行SET key value EX seconds
的效果等同於執行SETEX key seconds value
。PX milliseconds
: 將鍵的過期時間設置為milliseconds
毫秒。 執行SET key value PX milliseconds
的效果等同於執行PSETEX key milliseconds value
。NX
: 只在鍵不存在時, 才對鍵進行設置操作。 執行SET key value NX
的效果等同於執行SETNX key value
。XX
: 只在鍵已經存在時, 才對鍵進行設置操作。
Note
因為 SET
命令可以通過參數來實現 SETNX
、 SETEX
以及 PSETEX
命令的效果, 所以 Redis 將來的版本可能會移除並廢棄 SETNX
、 SETEX
和 PSETEX
這三個命令。
返回值
在 Redis 2.6.12 版本以前, SET
命令總是返回 OK
。
從 Redis 2.6.12 版本開始, SET
命令只在設置操作成功完成時才返回 OK
; 如果命令使用了 NX
或者 XX
選項, 但是因為條件沒達到而造成設置操作未執行, 那么命令將返回空批量回復(NULL Bulk Reply)。
代碼示例
對不存在的鍵進行設置:
redis> SET key "value" OK redis> GET key "value"
對已存在的鍵進行設置:
redis> SET key "new-value" OK redis> GET key "new-value"
使用 EX
選項:
redis> SET key-with-expire-time "hello" EX 10086 OK redis> GET key-with-expire-time "hello" redis> TTL key-with-expire-time (integer) 10069
使用 PX
選項:
redis> SET key-with-pexpire-time "moto" PX 123321 OK redis> GET key-with-pexpire-time "moto" redis> PTTL key-with-pexpire-time (integer) 111939
使用 NX
選項:
redis> SET not-exists-key "value" NX OK # 鍵不存在,設置成功 redis> GET not-exists-key "value" redis> SET not-exists-key "new-value" NX (nil) # 鍵已經存在,設置失敗 redis> GEt not-exists-key "value" # 維持原值不變
使用 XX
選項:
redis> EXISTS exists-key (integer) 0 redis> SET exists-key "value" XX (nil) # 因為鍵不存在,設置失敗 redis> SET exists-key "value" OK # 先給鍵設置一個值 redis> SET exists-key "new-value" XX OK # 設置新值成功 redis> GET exists-key "new-value"