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

}
相关推荐
肠畔码农10 分钟前
深度解密 Redis 分布式锁:从单机原子语义到集群架构博弈
redis·分布式·架构
肠畔码农2 小时前
Redis 主从复制内核深潜:从物理模型到全量增量同步的本质
网络·redis·php
三8443 小时前
PHP 污点分析绕过实战:CURL、get_meta_tags 与 fpm_get_status 引入非预定义污点源
开发语言·php
辻弋2014 小时前
一键优化电源计划、游戏模式、独显强制、禁用后台录制——DeltaForceBooster专治三角洲行动卡顿掉帧,所有改动可一键还原
服务器·数据库·windows·游戏·电脑·php
Sagittarius_A*5 小时前
【好靶场】PHP反序列化入门练习
安全·php·web·反序列化
2601_965798475 小时前
How to Build a Scalable Classified Directory with Classima Theme
php·theme
何以解忧,唯有..5 小时前
Python logging 模块:从入门到精通
python·microsoft·php
小的~~5 小时前
面试被问分布式锁,我差点语塞…直到搞懂了Redis、ZooKeeper和etcd的“三国杀”
redis·分布式·面试
quantdash_cc5 小时前
历史数据断层与REST请求慢到崩溃?QuantDash高性能量化数据API终极解决方案
开发语言·python·缓存·php·量化·quantdash
sbjdhjd6 小时前
CTF 技术复盘:从参数类型绕过到正则回溯 | Merry Christmas PHP CTF(gift.php & gift_plus.php)
安全·网络安全·云计算·php·ctf·红队·网络攻防