Skip to content

Instantly share code, notes, and snippets.

@muathendirangu
Created March 3, 2024 20:53
Show Gist options
  • Save muathendirangu/22fa47a9bab51c02fa6fefb4917a64e1 to your computer and use it in GitHub Desktop.
Save muathendirangu/22fa47a9bab51c02fa6fefb4917a64e1 to your computer and use it in GitHub Desktop.
Async processing in php using redis
// Breakdown of the script
```bash
composer require predis/predis
```
1. **Update the configuration file (`config.php`):**
```php
<?php
return [
'redis' => [
'host' => 'localhost',
'port' => 6379,
'queue' => 'async_tasks',
],
];
```
2. **Sender script (`send_task.php`):**
```php
<?php
require_once __DIR__ . '/vendor/autoload.php';
$config = require_once __DIR__ . '/config.php';
use Predis\Client;
// Connect to Redis
$redis = new Client([
'host' => $config['redis']['host'],
'port' => $config['redis']['port'],
]);
// Create a sample task
$task = [
'type' => 'send_email',
'data' => [
'to' => 'recipient@example.com',
'subject' => 'Hello!',
'body' => 'This is the email body.',
],
];
// Convert the task to JSON
$messageBody = json_encode($task);
// Push the message to the Redis list
$redis->lpush($config['redis']['queue'], $messageBody);
echo " [x] Task sent: {$messageBody}\n";
```
3. **Worker script (`worker.php`):**
```php
<?php
require_once __DIR__ . '/vendor/autoload.php';
$config = require_once __DIR__ . '/config.php';
use Predis\Client;
// Connect to Redis
$redis = new Client([
'host' => $config['redis']['host'],
'port' => $config['redis']['port'],
]);
echo " [*] Waiting for messages. To exit, press CTRL+C\n";
while (true) {
// Retrieve a task from the Redis list
$messageBody = $redis->brpop($config['redis']['queue'], 0)[1];
$task = json_decode($messageBody, true);
// Simulate processing time
sleep(5);
// Process the task based on its type
switch ($task['type']) {
case 'send_email':
// Example: Send an email
sendEmail($task['data']);
echo " [x] Email sent to {$task['data']['to']}\n";
break;
// Add more task types as needed
default:
echo " [x] Unknown task type\n";
}
}
function sendEmail($data)
{
// Email sending logic goes here
echo "Sending email to: {$data['to']}, Subject: {$data['subject']}, Body: {$data['body']}\n"; // for demo purposes
}
```
To test run the worker script and sender script in separate terminals
```bash
php worker.php
```
```bash
php send_task.php
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment