SET
Set to hold the string value
. If key
already holds a value, it is overwritten, regardless of its type. Any previous time to live associated with the key is discarded on successful SET
operation.
The SET
command supports a set of options that modify its behavior:
EX
seconds — Set the specified expire time, in seconds.EXAT
timestamp-seconds — Set the specified Unix time at which the key will expire, in seconds.PXAT
timestamp-milliseconds — Set the specified Unix time at which the key will expire, in milliseconds.NX
— Only set the key if it does not already exist.XX
— Only set the key if it already exist.- — Retain the time to live associated with the key.
GET
— Return the old string stored at key, or nil if key did not exist. An error is returned andSET
aborted if the value stored at key is not a string.
Note: Since the SET
command options can replace SETNX
, SETEX
, PSETEX
, GETSET
, it is possible that in future versions these commands will be deprecated and finally removed.
: OK
if SET
was executed correctly.
If the command is issued with the GET
option, the above does not apply. It will instead reply as follows, regardless if the SET
was actually performed:
Bulk string reply: the old string value stored at key.
: (nil)
if the key did not exist.
Note: The following pattern is discouraged in favor of the Redlock algorithm which is only a bit more complex to implement, but offers better guarantees and is fault tolerant.
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:
- 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.
The script should be called with EVAL ...script... 1 resource-name token-value