安装
安装服务端
根据官方的安装,一条命令搞定。
安装 Yii2 客户端扩展
在你 Yii2 项目中执行
$ composer require udokmeci/yii2-beanstalk "dev-master"
安装管理 Beanstalk 队列的 Web 系统
此项目是一个单独的系统,可以查看和管理队列任务
$ composer create-project ptrofimov/beanstalk_console -s dev path/to/install
使用
开启服务端
$ beanstalkd -l 127.0.0.1 -p 11300
Yii2 端使用
添加配置文件:
'components' => [
// ...
'beanstalk' => [
'class' => 'udokmeci\yii2beanstalk\Beanstalk',
'host' => 127.0.0.1, // default host
'port' => 11300,
'connectTimeout' => 1,
'sleep' => false, // or int for usleep after every job
],
// ...
],
执行队列在 console\controllers\WorkerController
里面:
<?php
/**
* Created by PhpStorm.
* User: yidashi
* Date: 16/8/16
* Time: 下午9:09
*/
namespace console\controllers;
use udokmeci\yii2beanstalk\BeanstalkController;
use yii\helpers\Console;
use Yii;
class WorkerController extends BeanstalkController
{
// Those are the default values you can override
const DELAY_PRIORITY = "1000"; //Default priority
const DELAY_TIME = 5; //Default delay time
// Used for Decaying. When DELAY_MAX reached job is deleted or delayed with
const DELAY_MAX = 3;
public function listenTubes(){
return ["tube"];
}
/**
*
* Pheanstalk\Job $job
* string self::BURY
* self::RELEASE
* self::DELAY
* self::DELETE
* self::NO_ACTION
* self::DECAY
*
*/
public function actionTube($job){
$sentData = $job->getData();
try {
// something useful here
/*if($everthingIsAllRight == true){
fwrite(STDOUT, Console::ansiFormat("- Everything is allright"."\n", [Console::FG_GREEN]));
//Delete the job from beanstalkd
return self::DELETE;
}
if($everthingWillBeAllRight == true){
fwrite(STDOUT, Console::ansiFormat("- Everything will be allright"."\n", [Console::FG_GREEN]));
//Delay the for later try
//You may prefer decay to avoid endless loop
return self::DELAY;
}
if($IWantSomethingCustom==true){
Yii::$app->beanstalk->release($job);
return self::NO_ACTION;
}
fwrite(STDOUT, Console::ansiFormat("- Not everything is allright!!!"."\n", [Console::FG_GREEN]));
//Decay the job to try DELAY_MAX times.
return self::DECAY;*/
// if you return anything else job is burried.
} catch (\Exception $e) {
//If there is anything to do.
fwrite(STDERR, Console::ansiFormat($e."\n", [Console::FG_RED]));
// you can also bury jobs to examine later
return self::BURY;
}
}
}
最后记得要执行你写的 Worker:
$ php yii worker
参考文献
原文链接: http://www.getyii.com/topic/531