What is the purpose of the setnx command in Redis?
In Redis, the SETNX command is used to set a specified key to a specified value only if that key does not already exist. More specifically, SETNX is short for “Set if Not eXists” and it will set the key-value pair only if the key does not already exist.
Here is the function and characteristics of the SETNX command:
- Check if not exists
- Set if not exists.
- I only need one choice.
- Can I ask you a quick question?
- Can you please rephrase this in English?
- Check if key does not exist to set a new value.
For example, here is an example of setting key-value pairs using the SETNX command:
127.0.0.1:6379> SETNX mykey "Hello"
(integer) 1
127.0.0.1:6379> GET mykey
"Hello"
127.0.0.1:6379> SETNX mykey "World"
(integer) 0
127.0.0.1:6379> GET mykey
"Hello"
In the example above, the SETNX command is first used to set the key “mykey” to the value “Hello”. Because the key did not exist before, it returns 1 indicating the successful setting. Then, attempting to use the SETNX command again to set the same key to the value “World” results in a return of 0 since the key “mykey” already exists, and therefore no action is taken.