1. 程式人生 > >php-resque :基於Redis的後臺任務系統

php-resque :基於Redis的後臺任務系統

為什麼使用php-resque?

php-resque 是輕量級後臺任務系統,基於Redis,功能設計簡單,配置靈活。相比MQ系統大而全的MQ系統,這個顯得小而美。

php-resque 角色劃分

  • Job 定義任務,是負責具體的業務邏輯。
  • Queue 佇列,負責Job存/取
  • Worker 從Queue中取Job來執行。 一般為PHP CLI模式下,後臺守護方式執行。

使用

install

  • 如果下載慢, 可以配置 composer 國內映象
composer config -g repo.packagist composer https://packagist.phpcomposer.com
  • 安裝php-resque

舊版

Composer:This package is abandoned and no longer maintained. The author suggests using the resque/php-resque package instead.

composer require  "chrisboulton/php-resque 1.2"

更新為新的擴充套件包:resque/php-resque

composer require resque/php-resque

編寫Job

DemoJob.php

<?php
class DemoJob
{
    public function perform()
    {
        // Work work work
        //echo $this->args['name'];
    }
}

入佇列操作

<?php

Resque::setBackend('localhost:6379');
$args = array(
      'name' => 'hanmeimei',
    );
Resque::enqueue('default', DemoJob::class, $args);

Worker程式碼

resque-worker.php

<?php
$redis_dsn = '127.0.0.1:6379';
putenv("REDIS_BACKEND=$redis_dsn");
// 引入佇列的入口程式
$resque = realpath(dirname(__FILE__) . '/vendor/chrisboulton/php-resque/resque.php');
require_once $resque;

啟動worker

php-resque 的環境變數有:

  • QUEUE – 這個是必要的,會決定 worker 要執行什麼任務,重要的在前,例如 QUEUE=notify,mail,log 。也可以設定為 QUEUE=* 表示執行所有任務。

  • APP_INCLUDE – 可選,載入檔案用的。可以設成 APP_INCLUDE=require.php ,在 require.php 中引入所有 Job 的 Class即可。

  • COUNT – 設定 worker 數量,預設是1 COUNT=5 。

  • REDIS_BACKEND – 設定 Redis 的 ip, port。如果沒設定,預設是連 localhost:6379 。

  • LOGGING, VERBOSE – 設定 log, VERBOSE=1 即可。

  • VVERBOSE – 比較詳細的 log, VVERBOSE=1 debug 的時候可以開出來看。

  • INTERVAL – worker 檢查 queue 的間隔,預設是五秒 INTERVAL=5 。

  • PIDFILE – 如果你是開單 worker,可以指定 PIDFILE 把 pid 寫入,例如 PIDFILE=/var/run/resque.pid 。

  • BACKGROUND 可以把 resque 丟到背景執行。或者使用 php resque.php &就可以了。

示例

QUEUE=counter php resque-worker.php

至此,php-resque的安裝和使用已經完畢。

後面的章節是工具外掛, 僅供參考。


介面 resque-web

監控 PHP-Resque 的執行狀況

安裝

gem install resque-web -v 0.0.8

執行

resque-web -p 40000

監控 supervisor

啟動服務

/usr/bin/python /usr/bin/supervisord -c /etc/supervisor/supervisord.conf

監控專案配置
/etc/supervisor/conf.d/lumen_resque.conf

[program:worker_lumen_resque]
directory=/home/wwwroot/mysite
command=php resque-worker.php
environment=QUEUE='default'

優點:

  • 可以配置 程式異常退出後自動重啟
  • 制定程式執行使用者
  • 可以設定程序數
  • 自動重啟
  • supervisord啟動後,自動啟動指令碼