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

}
相关推荐
Lhappy嘻嘻5 小时前
Java IO|File 文件操作 + 字节流 / 字符流完整笔记 + 递归删除文件实战
java·笔记·php
ffqws_5 小时前
Redis 分布式锁:基于 Redisson 的实现与面试高频问答
redis·分布式·面试
2601_963771377 小时前
How to Scale Your WordPress Store Traffic in 2026
前端·php·plugin
六bring个六11 小时前
open Harmony中分布式软总线的学习任务清单
分布式·学习·c/c++·open harmony
wuqingshun31415911 小时前
说一下 Kafka 中关于事务消息的实现?
分布式·kafka
右耳朵猫AI11 小时前
PHP周刊2026W28 | 安全更新、Laravel 13.18、Twig 3.28
开发语言·php·laravel
罗政12 小时前
PDF 批量合并工具:本地 AI 自动排序、识别正文日期与合同编号
数据库·pdf·php
糖果店的幽灵13 小时前
安全测试从入门到精通_网络基础与HTTPS
网络·https·php
2601_9637713714 小时前
WordPress SEO Guide: Boost Rankings Without Technical Jargon
前端·php
名字还没想好☜16 小时前
用 Redis + Redisson 实现分布式锁:从踩坑到生产可用
java·redis·分布式·junit·分布式锁·redisson