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

}
相关推荐
Risehuxyc6 小时前
来自PHP项目devnexen的回信
开发语言·php
饿了吃洗衣凝珠9 小时前
SELinux
服务器·开发语言·php
筑梦之人9 小时前
Elasticsearch 9.x 从入门到精通(5/7):集群、分布式与运维
运维·分布式·elasticsearch
普通人69 小时前
PHP多维数组排序完全指南
开发语言·php·1024程序员节
码农小河661 天前
基于PHP的电商后台蜜罐系统
开发语言·php
阿洛学长1 天前
PHP开发框架对比:Laravel、Yii、Tp、Yaf、Swoole
php·laravel·swoole
Risehuxyc1 天前
GetCpolar留V3版去掉V2版
php
FYKJ_20101 天前
springboot同人周边订单管理系统48955-计算机毕业设计、课程设计
java·javascript·vue.js·spring boot·django·php·课程设计
kiwixing1 天前
GaussDB|集中式还是分布式?三把尺子选型
分布式·gaussdb
真上帝的左手2 天前
30. 技术专题-‌应用框架组件-分布式架构
分布式·架构·系统架构·分布式架构