What is the usage of the setnx command in Redis?
The SETNX command in Redis is a string command used to set the value of a key only if the key does not already exist. If the key already exists, the SETNX command will not perform any operation.
Here is how the SETNX command is used:
SETNX key value
In this case, key represents the key that needs to be set, and value represents the value that needs to be set.
There are two possible outcomes when using the SETNX command.
- When the key does not exist, the SETNX command executes successfully, the set is successful, and returns 1.
- When the key already exists, the SETNX command fails to execute, fails to set, and returns 0.
The SETNX command is commonly used in practice to create distributed locks. By setting the value of a key with the SETNX command, mutual exclusion access can be achieved among multiple processes or threads. When multiple processes are executing the SETNX command simultaneously, only one process can successfully set the value of the key, while the others will fail. Therefore, this mechanism can be used to achieve the effect of a mutual exclusion lock.