predisHow can I use the Redis setnx command in PHP?
The setnx
command in Redis is used to set a key only if it does not already exist. This can be used to ensure that a key is only ever set once.
In PHP, the setnx
command can be used with the Redis
class. The following example code will set the key mykey
to the value myvalue
only if the key does not already exist:
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$set = $redis->setnx('mykey', 'myvalue');
echo $set;
The output of the example code will be 1
if the key is successfully set, or 0
if the key already exists.
The parts of the example code are:
$redis = new Redis();
- creates a new instance of theRedis
class.$redis->connect('127.0.0.1', 6379);
- connects to the Redis server.$set = $redis->setnx('mykey', 'myvalue');
- sets the keymykey
to the valuemyvalue
only if it does not already exist.echo $set;
- prints the result of thesetnx
command.
For more information, see the PHP Redis documentation.
More of Predis
- How can I use PHP and Redis to retrieve a range of values from a sorted set?
- How can I use PHP and Redis to get a reverse range of scores?
- How can I troubleshoot a "PHP Redis went away" error?
- How can I use the zscan command in PHP with Redis?
- How can I use Predis with a cluster in PHP?
- How do I install and configure a PHP Redis DLL on a Windows machine?
- How do I install PHP Redis on Ubuntu 20.04?
- How do I use PHP and Redis together to create a transaction?
- How can I use PHP and Redis to set a time-to-live (TTL) value?
- How can I use Redis with the Yii PHP framework?
See more codes...