动态

详情 返回 返回

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

}
user avatar zjkal 头像 pottercoding 头像 menglihuaxiangbian 头像 guangmingleiluodetouyingyi_bccdlf 头像
点赞 4 用户, 点赞了这篇动态!
点赞

Add a new 评论

Some HTML is okay.