resque / yii2-resque
Yii2 Resque
dev-master
2015-05-22 05:54 UTC
This package is not auto-updated.
Last update: 2024-09-14 16:55:35 UTC
README
Resque 是一个基于 Redis 的库,用于创建后台任务,将这些任务放入一个或多个队列中,并在稍后进行处理。
需求
- php pcntl extension.
- Redis.io
- phpredis extension for better performance, otherwise it'll automatically use Credis as fallback.
- Yii 2
安装
-
通过 composer 安装此扩展是首选方式。
添加
"repositories":[ { "type": "git", "url": "https://github.com/sprytechies/yii2-resque.git" } ],
运行以下命令:
php composer.phar require --prefer-dist resque/yii2-resque "*"
或者将以下内容添加到您的
composer.json
文件的 require 部分中。"resque/yii2-resque": "dev-master"
在 app/commands 文件夹中创建一个名为
ResqueController.php
的文件(对于 yii2-basic),或者对于 yii2-advanced,在 console/controllers 中创建。在其中写入以下代码。 -
请确保您已经安装了
Yii2-redis
扩展。namespace app\commands; use Yii; use yii\console\Controller; use resque\lib\ResqueAutoloader; use resque\lib\Resque\Resque_Worker; /** * * @author Sprytechies * @since 2.0 */ class ResqueController extends Controller { /** * This command echoes what you have entered as the message. * @param string $message the message to be echoed. */ public function actionIndex() { $includeFiles=getenv('INCLUDE_FILES'); if ($includeFiles) { $includeFiles = explode(',', $includeFiles); foreach ($includeFiles as $file) { require_once $file; } } if(file_exists(Yii::getAlias('@app') . '/config/console.php')){ // Yii2-Basic $config = require(Yii::getAlias('@app') . '/config/console.php'); }else { // Yii2-Advance $config = require(Yii::getAlias('@app') . '/config/main.php'); } $application = new \yii\console\Application($config); # Turn off our amazing library autoload spl_autoload_unregister(array('Yii','autoload')); if(file_exists(Yii::getAlias('@vendor') . '/resque/yii2-resque/ResqueAutoloader.php')){ // Yii2-Basic require_once(Yii::getAlias('@vendor') . '/resque/yii2-resque/ResqueAutoloader.php'); }else { // Yii2-Advance require_once(Yii::getAlias('@app') . '/../vendor/resque/yii2-resque/ResqueAutoloader.php'); } ResqueAutoloader::register(); # Give back the power to Yii spl_autoload_register(array('Yii','autoload')); $QUEUE = getenv('QUEUE'); if(empty($QUEUE)) { die("Set QUEUE env var containing the list of queues to work.\n"); } $REDIS_BACKEND = getenv('REDIS_BACKEND'); $REDIS_BACKEND_DB = getenv('REDIS_BACKEND_DB'); $REDIS_AUTH = getenv('REDIS_AUTH'); if(!empty($REDIS_BACKEND)) { $REDIS_BACKEND_DB = (!empty($REDIS_BACKEND_DB)) ? $REDIS_BACKEND_DB : 0; Resque::setBackend($REDIS_BACKEND, $REDIS_BACKEND_DB, $REDIS_AUTH); } $logLevel = 0; $LOGGING = getenv('LOGGING'); $VERBOSE = getenv('VERBOSE'); $VVERBOSE = getenv('VVERBOSE'); if(!empty($LOGGING) || !empty($VERBOSE)) { $logLevel = Resque_Worker::LOG_NORMAL; } else if(!empty($VVERBOSE)) { $logLevel = Resque_Worker::LOG_VERBOSE; } $logger = null; $LOG_HANDLER = getenv('LOGHANDLER'); $LOG_HANDLER_TARGET = getenv('LOGHANDLERTARGET'); if (class_exists('MonologInit_MonologInit')) { if (!empty($LOG_HANDLER) && !empty($LOG_HANDLER_TARGET)) { $logger = new MonologInit_MonologInit($LOG_HANDLER, $LOG_HANDLER_TARGET); } else { fwrite(STDOUT, '*** loghandler or logtarget is not set.'."\n"); } } else { fwrite(STDOUT, '*** MonologInit_MonologInit logger cannot be found, continue without loghandler.'."\n"); } $interval = 5; $INTERVAL = getenv('INTERVAL'); if(!empty($INTERVAL)) { $interval = $INTERVAL; } $count = 1; $COUNT = getenv('COUNT'); if(!empty($COUNT) && $COUNT > 1) { $count = $COUNT; } $PREFIX = getenv('PREFIX'); if(!empty($PREFIX)) { fwrite(STDOUT, '*** Prefix set to '.$PREFIX."\n"); Resque::redis()->prefix($PREFIX); } if($count > 1) { for($i = 0; $i < $count; ++$i) { $pid = Resque::fork(); if($pid == -1) { die("Could not fork worker ".$i."\n"); } // Child, start the worker else if(!$pid) { startWorker($QUEUE, $logLevel, $logger, $interval); break; } } } // Start a single worker else { $PIDFILE = getenv('PIDFILE'); if ($PIDFILE) { file_put_contents($PIDFILE, getmypid()) or die('Could not write PID information to ' . $PIDFILE); } $this->startWorker($QUEUE, $logLevel, $logger, $interval); } } function startWorker($QUEUE, $logLevel, $logger, $interval) { $queues = explode(',', $QUEUE); $worker = new Resque_Worker($queues); if (!empty($logger)) { $worker->registerLogger($logger); } else { fwrite(STDOUT, '*** Starting worker '.$worker."\n"); } $worker->logLevel = $logLevel; $worker->work($interval); } }
-
将这些内容添加到您的 config/web.php 和 config/console.php(对于 yii2-basic)或 console/config/main.php 和 common/config/main-local.php(对于 yii2-advanced)中。
'components' => [ ... 'resque' => [ 'class' => '\resque\RResque', 'server' => 'localhost', // Redis server address 'port' => '6379', // Redis server port 'database' => 0, // Redis database number 'password' => '', // Redis password auth, set to '' or null when no auth needed ], ... ]
-
确保您已经安装了
Yii2-redis
扩展。
用法
扩展安装后
-
在您的应用(yii2-basic)中创建一个名为
components
的文件夹。对于 yii2-advanced 模板,在 app(例如 frontend)中创建此文件夹。您可以将所有类文件放入此components
文件夹中。根据您的应用更改命名空间。示例 -
namespace app\components; class ClassWorker { public function setUp() { # Set up environment for this job } public function perform() { echo "Hello World"; # Run task } public function tearDown() { # Remove environment for this job } }
创建任务和工作者 ----------------------
You can put this line where ever you want to add jobs to queue
```php
Yii::$app->resque->createJob('queue_name', 'ClassWorker', $args = []);
```
Put your workers inside `components` folder, e.g you want to create worker with name SendEmail then you can create file inside `components` folder and name it SendEmail.php, class inside this file must be SendEmail
创建延迟任务 ------------------
You can run job at specific time
```php
$time = 1332067214;
Yii::$app->resque->enqueueJobAt($time, 'queue_name', 'ClassWorker', $args = []);
```
or run job after n second
```php
$in = 3600;
$args = ['id' => $user->id];
Yii::$app->resque->enqueueIn($in, 'email', 'ClassWorker', $args);
```
Get Current Queues
------------------
This will return all job in queue (EXCLUDE all active job)
```php
Yii::$app->resque->getQueues();
```
Start and Stop workers
----------------------
Run this command from your console/terminal :
Start queue
`QUEUE=* php yii resque start`
Stop queue
`QUEUE=* php yii resque stop`