安装
linux安装(window用户我暂时没有更好的方案,请安装虚拟机,我使用的是vagrant)
yum install beanstalk
yii2项目安装
composer require udokmeci/yii2-beanstalk "dev-master"
安装管理 Beanstalk 队列的 Web 系统,此项目是一个单独的系统,可以查看和管理队列任务
composer create-project ptrofimov/beanstalk_console -s dev beanstalk_console
如何使用
首先,服务端开启
beanstalkd -l 127.0.0.1 -p 11300
yii2 console 模块中配置
main.php
'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
],
// ...
],
'controllerMap' => [
'worker'=>[
'class' => 'app\commands\WorkerController',
]
],
执行队列在 console\controllers\WorkerController 里面:
<?php
namespace app\commands;
use common\helpers\ObjectHelper;
use common\models\MongoTrack;
use common\services\TrackService;
use Pheanstalk\Job;
use udokmeci\yii2beanstalk\BeanstalkController;
use Yii;
class WorkerController extends BeanstalkController
{
/**
* @var integer 优先级 值越小优先级越高,默认为1024
*/
const DELAY_PRIORITY = 1000;
/**
* @var integer 延迟执行的秒数
*/
const DELAY_TIME = 5;
/**
* @var integer 当 delay_max 达到 删除或延迟
*/
const DELAY_MAX = 3;
public function listenTubes()
{
return ['tube', 'track'];
}
/**
* 采集数据
* @param $job Job
* @return string
*/
public function actionTrack($job)
{
/** @var object $sentData */
$sentData = $job->getData();
if (TrackService::isNeedTrack($sentData->unique_id, $sentData->source, $sentData->method)) {
$model = new MongoTrack();
$model->load(ObjectHelper::toArray($sentData), '');
fwrite(STDOUT, json_encode($model->errors));
if ($model->save()) {
return self::DELETE;
}
fwrite(STDOUT, json_encode($model->errors));
return self::BURY;
}
// 不需要保存 mongodb 删除
return self::DELETE;
}
// ...
}
然后执行php yii worker
安装管理 Beanstalk 队列的 Web 系统,此项目是一个单独的系统,可以查看和管理队列任务
composer create-project ptrofimov/beanstalk_console -s dev beanstalk_console
安装完成后将域名指向beanstalk_console/public目录下,可查看哥哥tube队列状态
问题:linux 启动进程yii worker 进程后,关闭xshell,如何保证进程不关闭?有待探索