How to Implement a Redis‑Backed Queue in ThinkPHP5
This guide explains how to set up ThinkPHP5's built‑in Queue component with a Redis driver, create a custom queue class, configure the queue, produce messages, and run a consumer process, including handling retries, delays, and daemon mode.
Overview
ThinkPHP5 provides a Queue component with four drivers (Redis, Database, Topthink, Sync). This tutorial focuses on the Redis driver, which is suitable for high‑concurrency tasks such as sending emails, SMS, or push notifications.
Creating a Queue Job
Place the job class at application\common\queue\TestQueue.php:
<?php
namespace app\common\queue;
use think\facade\Log;
use think\queue\Job;
class TestQueue {
public function fire(Job $job, $data) {
$isJobDone = $this->testJob($data);
if ($isJobDone) {
$job->delete();
} else {
$attempts = $job->attempts();
echo $attempts;
if ($attempts == 0 || $attempts == 1) {
$job->release(2); // retry after 2 s
} elseif ($attempts == 2) {
$job->release(5); // retry after 5 s
}
}
}
/**
* Called when the job exceeds the maximum retry count.
*/
public function failed($data) {
Log::error('Job failed after max retries: '.json_encode($data));
}
/**
* Your business logic.
*/
private function testJob($data) {
$jsonData = json_encode($data);
echo "1、Received parameters: {$jsonData}
";
if ($data) {
echo "2、Success! {$data['email']} sent.
";
return true;
} else {
echo "2、Failure! {$data['email']} not sent.
";
return false;
}
}
}
?>Queue Configuration
Configure the Redis driver in application\config\queue.php:
return [
'connector' => 'Redis',
'expire' => 3600,
'default' => 'REDIS_QUEUE',
'host' => 'dnmp-redis',
'port' => 6379,
'password' => '',
'select' => 0,
'timeout' => 0,
'persistent'=> false,
];Producer Code
Push a job onto the queue:
public function productMsg() {
$data = [
'email' => rand(11,99)."@qq.com",
'username' => 'Tinywan',
];
$queueName = 'testQueue';
$isPushed = Queue::push(TestQueue::class, $data, $queueName);
if ($isPushed !== false) {
echo "[{$data['email']}] 队列加入成功
";
} else {
echo "队列加入失败
";
}
}Run the producer with php product_msg.php. The message is stored in Redis as a list entry such as queues:testQueue.
Consumer (Worker) Execution
Start a worker to process the queue:
# php think queue:work --queue testQueueThe worker prints the received parameters and a success message, then deletes the job. Use --daemon to keep the process running, --delay to set a retry delay, and --memory to limit memory usage.
When the worker runs in daemon mode, code changes require a php think queue:restart to take effect.
Monitoring Redis Queue
Typical Redis commands to inspect the queue:
docker exec -it dnmp-redis redis-cli
keys *
TYPE queues:testQueue
LRANGE queues:testQueue 0 -1After a job is processed, the corresponding list element is removed.
Running as a Background Process
Use nohup to start the daemonized worker in the background:
nohup /usr/bin/php /var/www/tp5/think queue:work --daemon --queue testQueue --memory 256 >/dev/null 2>/dev/null &Check the process list with ps aux | grep queue to verify it is running.
Key Takeaways
ThinkPHP5 Queue abstracts message‑queue operations; Redis provides persistence and fast list operations.
Define a job class with fire, failed, and custom business logic.
Configure connection parameters in queue.php.
Producer pushes jobs; consumer processes them, handling retries and delays.
Daemon mode enables continuous processing; restart is required after code changes.
This setup allows you to offload time‑consuming tasks (email, SMS, video conversion, etc.) to a reliable asynchronous system, improving overall application performance.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Open Source Tech Hub
Sharing cutting-edge internet technologies and practical AI resources.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
