yii2-queue 的使用
- 安装
composer require --prefer-dist yiisoft/yii2-queue
- 配置,在 common/config/main.php 中配置
return [
'bootstrap' => [
'queue', // 把这个组件注册到控制台
'log'
],
'components' => [
'cache' => [
'class' => 'yii\caching\FileCache',
],
'redis' => [
'class' => 'yii\redis\Connection',
'hostname' => '127.0.0.1',
'port' => 6379,
'password' => '',
'database' => 0
],
'queue' => [
'class' => \yii\queue\redis\Queue::class,
'as log' => \yii\queue\LogBehavior::class,
'channel' => 'queue',
],
],
];
- 新建 common/jobs/OrderCancelJob
class OrderCancelJob extends BaseObject implements JobInterface
{
public $orderId;
/**
* @param Queue $queue which pushed and is handling the job
*/
public function execute($queue)
{
$t = \Yii::$app->db->beginTransaction();
try {
echo "队列-订单号:{$this->orderId}\r\n";
//to do 处理业务
$t->commit();
} catch (\Exception $exception) {
$t->rollBack();
}
}
}
- 启动控制台监听队列
php yii queue/listen
使用队列
将任务添加到队列:
Yii::$app->queue->push(new OrderCancelJob([
'orderId' => '2022031425555555'
]));
将作业推送到队列中延时5分钟运行:
Yii::$app->queue->delay(5 * 60)->push(new OrderCancelJob([
'orderId' => '2022031425555555'
]));
重要: 只有一部分驱动支持延时运行。
宝塔安装Supervisor管理器守护进程
- 安装 Supervisor
添加进程举例内容
进程名称: yii-queue-worker
启动用户: root
运行目录: www/wwwroot
启动命令: php yii queue/listen
进程数量: 1