Yii实现RabbitMQ队列

一:拓展安装

复制代码
composer require yiisoft/yii2-queue
composer require enqueue/amqp-lib

2:RabbitMQ队列配置

在配置文件中配置RabbitMQ队列

复制代码
'components' => [
    ...
    'queue' => [
        'class' => yii\queue\amqp_interop\Queue::class,
        'host' => '192.168.6.88',//host
        'port' => '5672',//端口
        'user' => 'admin',//账号
        'password' => 'admin',//密码
        'queueName' => 'queue',//队列名称
        'ttr' => 300,//任务处理最长时间(秒)
        'attempts' => 3,//任务最大尝试次数
    ],
    ...
]

在配置文件的bootstrap属性增加queue

复制代码
'bootstrap' => [
    ...
    'queue',
    ...
],

3:发送队列任务

复制代码
Yii::$app->queue->push(new TestJobs([
    'message' => 'hello world'
]));

4:接收并处理队列任务

复制代码
<?php
namespace console\jobs;

use Yii;
use yii\base\BaseObject;
use yii\queue\JobInterface;

class TestJobs extends BaseObject implements JobInterface
{
    public $message;
    
    public function execute($queue)
    {
        var_dump($this->message);
        return true;
    }

}

如果我们需要在执行队列任务时只有执行成功才删除对应的任务,否则不删除处理

复制代码
<?php
namespace console\jobs;

use Yii;
use yii\base\BaseObject;
use yii\queue\RetryableJobInterface;

class TestJobs extends BaseObject implements RetryableJobInterface
{
    public $message;

    public function execute($queue)
    {
        if ($this->message == 'hello world') {
            return true;
        }

        return false;
    }

    /**
     * 任务处理最长时间(秒)
     */
    public function getTtr()
    {
        return 300;
    }

    /**
     * 失败后是否需要执行
     * 返回true表示失败后需要重新执行
     */
    public function canRetry($attempt, $error)
    {
        return true;
    }

}
相关推荐
做个文艺程序员1 天前
私有 LLM 多机多卡分布式推理:Pipeline Parallel vs Tensor Parallel 踩坑全记录
人工智能·分布式
fzb5QsS1p1 天前
告别重复造轮子,Qt 快速开发脚手架
开发语言·qt·php
foundbug9991 天前
Matlab基于分布式模型预测控制的多固定翼无人机共识控制
分布式·matlab·无人机
取码网1 天前
最新临时文件快传系统源码 轻量化 带后台
php
彧翎Pro1 天前
ASP.NET Core 外部依赖调用治理实战:HttpClientFactory、Polly 与幂等边界
microsoft·asp.net·php
wenzhangli71 天前
ooderAgent 龙虾时代的统一认证体系
开发语言·php
一个有温度的技术博主1 天前
Redis集群实战:如何实现节点的弹性伸缩与数据迁移?
redis·分布式·缓存·架构
cch89181 天前
Laravel vs ThinkPHP:PHP框架终极对决
android·php·laravel
morrisonwu1 天前
kafka4.2对应php rdkafka扩展安装以及php的producer和consumer写法及避坑
开发语言·php
李白的天不白1 天前
php处理跨域请求
php