在 Ubuntu + ThinkPHP 环境下使用队列,一般是通过 ThinkPHP 官方队列扩展 topthink/think-queue 来实现。下面按从零开始的步骤说明。
sudo apt update
sudo apt install php php-cli php-mbstring php-dom php-curl php-zip
确认 PHP 版本:
php -v
composer create-project topthink/think tp-queue
cd tp-queue
composer require topthink/think-queue
编辑 config/queue.php
常见配置示例(Redis):
return [
'default' => 'redis',
'connections' => [
'redis' => [
'type' => 'redis',
'queue' => 'default',
'host' => '127.0.0.1',
'port' => 6379,
'password' => '',
'select' => 0,
'timeout' => 0,
'persistent' => false,
],
],
];
如果使用数据库队列:
php think queue:table
php think migrate
php think queue:job
或手动创建:
<?php
namespace app\job;
use think\queue\Job;
class TestJob
{
public function fire(Job $job, $data)
{
// 处理任务
echo "处理任务:" . $data['name'] . PHP_EOL;
// 删除任务
$job->delete();
}
// 失败处理
public function failed($data)
{
// 记录日志
}
}
use think\facade\Queue;
Queue::push(\app\job\TestJob::class, ['name' => 'ThinkPHP']);
或延迟执行:
Queue::later(60, \app\job\TestJob::class, ['name' => '延迟任务']);
php think queue:work
或:
php think queue:listen
work性能更好,listen适合开发
sudo apt install supervisor
sudo nano /etc/supervisor/conf.d/queue.conf
内容:
[program:think-queue]
command=php /var/www/tp-queue/think queue:work
autostart=true
autorestart=true
user=www-data
redirect_stderr=true
stdout_logfile=/var/log/queue.log
sudo supervisorctl reread
sudo supervisorctl update
sudo supervisorctl start think-queue
queue:workphp think queue:failed
php think queue:retry all
写 Job → 推送 Queue → 启动 Worker → 自动消费
如果你用的是 ThinkPHP 6 / 8、Redis / 数据库队列、或 Docker 环境,可以告诉我,我可以给你更具体的配置示例。