key to hold the string
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:
EXseconds -- Set the specified expire time, in seconds.
PXmilliseconds -- Set the specified expire time, in milliseconds.
EXATtimestamp-seconds -- Set the specified Unix time at which the key will expire, in seconds.
PXATtimestamp-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.
KEEPTTL-- Retain the time to live associated with the key.
- GET -- Return the old value stored at key, or nil when key did not exist.
Simple string reply:
OK if SET was executed correctly.
Bulk string reply: when GET option is set, the old value stored at key, or nil when key did not exist.
Null reply: a Null Bulk Reply is returned if the SET operation was not performed because the user specified the
XX option but the condition was not met, or if the user specified the GET option and there was no previous value for the key.
>= 2.6.12: Added the
>= 6.0: Added the
>= 6.2: Added the GET,
"OK"redis> GET mykey
"Hello"redis> SET anotherkey "will expire in a minute" EX 60
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.
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:
- Instead of setting a fixed string, set a non-guessable large random string, called token.
- 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.
An example of unlock script would be similar to the following:
if redis.call("get",KEYS) == ARGV then return redis.call("del",KEYS) else return 0 end
The script should be called with
EVAL ...script... 1 resource-name token-value