predisHow can I use a Redis job queue in a PHP application?
A Redis job queue can be used in a PHP application to process asynchronous tasks in the background. This can be done by pushing tasks onto a Redis queue, and then having a worker process that pulls tasks off the queue and executes them.
Example code
// Push a job to the queue
$redis->rpush('queue', json_encode(['task' => 'sendEmail', 'params' => ['to' => '[email protected]']]));
// Worker process to pull jobs from the queue
while($job = $redis->lpop('queue')) {
$job = json_decode($job, true);
switch ($job['task']) {
case 'sendEmail':
sendEmail($job['params']['to']);
break;
}
}
function sendEmail($to) {
// Send an email to $to
echo "Sending an email to $to\n";
}
Output example
Sending an email to [email protected]
Code explanation
-
$redis->rpush('queue', json_encode(['task' => 'sendEmail', 'params' => ['to' => '[email protected]']]));
- This line pushes a job onto the Redis queue. The job is encoded as JSON and contains two pieces of information - the task to be executed, and the parameters to be passed to the task. -
while($job = $redis->lpop('queue')) {
- This line starts an infinite loop that pulls jobs off the queue and executes them. -
$job = json_decode($job, true);
- This line decodes the job from JSON. -
switch ($job['task']) {
- This line checks the task name in the job and executes the appropriate code based on that. -
sendEmail($job['params']['to']);
- This line calls thesendEmail
function and passes it theto
parameter from the job. -
function sendEmail($to) {
- This is thesendEmail
function which is called by the code above. It simply prints a message indicating that an email was sent.
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 Predis with a cluster in PHP?
- How do I install and configure a PHP Redis DLL on a Windows machine?
- How can I install and configure PHP and Redis on a Windows system?
- How can I use the zscan command in PHP with Redis?
- How can I use PHP to increment values in Redis using ZINCRBY?
- How can I use Redis with the Yii PHP framework?
- How can I configure TLS encryption for a connection between PHP and Redis?
- How can I use PHP and Redis to retrieve data from a sorted set using ZRANGEBYSCORE?
- How do I use the PHP Redis zrevrange command?
See more codes...