赞
踩
- composer require yiisoft/yii2-queue
- composer require enqueue/amqp-lib
在配置文件中配置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',
- ...
- ],
- Yii::$app->queue->push(new TestJobs([
- 'message' => 'hello world'
- ]));
- <?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;
- }
-
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。