predisHow do I use PHP to subscribe to Redis?
Using PHP to subscribe to Redis is easy.
First, you need to install the phpredis extension for PHP. This can be done with pecl install redis
.
Then you can use the following code to subscribe to a Redis channel:
<?php
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$redis->subscribe(array('channel1', 'channel2'), function($redis, $channel, $message) {
echo "Channel $channel received $message\n";
});
?>
This will subscribe to the two channels channel1
and channel2
. When a message is sent to either of these channels, the callback function will be called with the channel name and the message as parameters.
Code explanation
$redis = new Redis();
: Creates a new Redis instance.$redis->connect('127.0.0.1', 6379);
: Connects to the Redis server.$redis->subscribe(array('channel1', 'channel2'), function($redis, $channel, $message) {...});
: Subscribes to the channelschannel1
andchannel2
.echo "Channel $channel received $message\n";
: Prints the channel name and message when a message is received.
Helpful links
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 to increment values in Redis using ZINCRBY?
- How can I use Predis with a cluster in PHP?
- How do I check the version of PHP Redis?
- How can I use PHP and Redis to retrieve data from a sorted set using ZRANGEBYSCORE?
- How do I install PHP Redis on Ubuntu 20.04?
- How can I troubleshoot a "PHP Redis went away" error?
- How do I install and configure a PHP Redis DLL on a Windows machine?
- How can I check the version of PHP and Redis I am using?
- How do I use hmset in PHP with Redis?
See more codes...