redis - set key value [expiration EX seconds|PX milliseconds] [NX|XX]
**set key value [expiration EX seconds|PX milliseconds] [NX|XX]**
Redis 2.6.12以降、SETコマンドは設定操作が正常に完了した場合にのみOKを返します.コマンドがNXまたはXXオプションを使用しているが、条件が満たされていないために設定操作が実行されていない場合、コマンドは空の一括返信(NULL Bulk Reply)を返します.
例
#######既存の値を設定すると上書きされます
127.0.0.1:6379[2]> set key "value"
OK
127.0.0.1:6379[2]> get key
"value"
127.0.0.1:6379[2]> set key "new-value"
OK
127.0.0.1:6379[2]> get key
"new-value"
127.0.0.1:6379[2]>
######EXオプションの使用
127.0.0.1:6379[2]> set key-expire-time "value" ex 20
OK
127.0.0.1:6379[2]> get key-expire-time
"value"
127.0.0.1:6379[2]> ttl key-expire-time
(integer) 12
127.0.0.1:6379[2]> ttl key-expire-time
(integer) 10
127.0.0.1:6379[2]> ttl key-expire-time
(integer) 10
127.0.0.1:6379[2]> ttl key-expire-time
(integer) 9
127.0.0.1:6379[2]> get key-expire-time
"value"
127.0.0.1:6379[2]> get key-expire-time
(nil)
127.0.0.1:6379[2]>
127.0.0.1:6379[2]> SETEX key-expire-time-nx 10 "hello"
OK
127.0.0.1:6379[2]> get key-expire-time-nx
"hello"
127.0.0.1:6379[2]> ttl key-expire-time-nx
(integer) 2
127.0.0.1:6379[2]> ttl key-expire-time-nx
(integer) 1
127.0.0.1:6379[2]> ttl key-expire-time-nx
(integer) -2
127.0.0.1:6379[2]> get key-expire-time-nx
(nil)
127.0.0.1:6379[2]>
127.0.0.1:6379[2]> PSETEX key-expire-time-px 10086 "px-hello"
OK
127.0.0.1:6379[2]> get key-expire-time-px
"px-hello"
127.0.0.1:6379[2]> PTTL key-expire-time-px
(integer) 303
127.0.0.1:6379[2]> PTTL key-expire-time-px
(integer) -2
127.0.0.1:6379[2]> get key-expire-time-px
(nil)
127.0.0.1:6379[2]>
nxはキーが存在しない場合にのみキーを設定操作する
127.0.0.1:6379[2]> EXISTS not-exists-key
(integer) 0
127.0.0.1:6379[2]> set not-exists-key "value" nx
OK
127.0.0.1:6379[2]> get not-exists-key
"value"
127.0.0.1:6379[2]> set not-exists-key "new-value" nx
(nil) #
127.0.0.1:6379[2]> get not-exists-key
"value" #
xxキーが存在する場合のみ、キーの設定操作を行う
127.0.0.1:6379[2]> EXISTS exists-key
(integer) 0 # key
127.0.0.1:6379[2]> SET exists-key "value" xx
(nil) # xx
127.0.0.1:6379[2]> SET exists-key "value"
OK # key-value
127.0.0.1:6379[2]> SET exists-key "new-value" xx
OK # xx
127.0.0.1:6379[2]> get exists-key
"new-value" #
127.0.0.1:6379[2]>