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;
    }

}
相关推荐
猫林老师6 小时前
HarmonyOS线程模型与性能优化实战
数据库·分布式·harmonyos
在未来等你10 小时前
Elasticsearch面试精讲 Day 26:集群部署与配置最佳实践
大数据·分布式·elasticsearch·搜索引擎·面试
勤源科技10 小时前
分布式链路追踪中的上下文传播与一致性维护技术
分布式
互联网工匠10 小时前
分布式操作的一致性方案
分布式·架构
熊猫钓鱼>_>10 小时前
【案例实战】鸿蒙分布式智能办公应用的架构设计与性能优化
分布式·华为·harmonyos
偶尔贪玩的骑士11 小时前
Kioptrix Level 1渗透测试
linux·开发语言·网络安全·php
迎風吹頭髮12 小时前
Linux服务器编程实践58-getnameinfo函数:通过socket地址获取主机名与服务名
开发语言·数据库·php
探索宇宙真理.13 小时前
WordPress Flex QR Code Generator文件上传 | CVE-2025-10041 复现&研究
经验分享·php·安全漏洞
PFinal社区_南丞14 小时前
构建可维护的正则表达式系统-pfinal-regex-center设计与实现
后端·php
没有bug.的程序员14 小时前
金融支付分布式架构实战:从理论到生产级实现
java·分布式·微服务·金融·架构·分布式调度系统