PHP使用QPM實現多進程並行任務處理常式,phpqpm

來源:互聯網
上載者:User

PHP使用QPM實現多進程並行任務處理常式,phpqpm

考慮用PHP實現以下情境: 有一個抓站的URL列表儲存在隊列裡,背景程式讀取這個隊列,然後轉交給子進程去抓取HTML存放到檔案裡。 為了提高效率,允許多任務並存執行,但為了避免機器負載過高,限制了最大的並行任務數(為了測試方便,我們把這個數設為3),當隊列中取到 END標記時,程式結束運行。

這個情境用QPM的Supervisor::taskFactoryMode()實現,非常簡單。

QPM全名是 Quick Process Management Module for PHP. PHP 是強大的web開發語言,以至於大家常常忘記PHP 可以用來開發健壯的命令列(CLI)程式以至於daemon程式。 而編寫daemon程式免不了與各種進程管理打交道。QPM正式為簡化進程管理而開發的類庫。QPM的項目地址是:https://github.com/Comos/qpm

為了,簡化測試環境,我們可以用一個文字檔來類比隊列的資料。完整的例子檔案看這裡:spider_task_factory_data.txt

http://news.sina.com.cn/http://news.ifeng.com/http://news.163.com/http://news.sohu.com/http://ent.sina.com.cn/http://ent.ifeng.com/...END

使用QPM的taskFactoryMode之前,我們需要準備一個TaskFactory類。 我們將其命名為 SpiderTaskFactory,SpdierTaskFactory 的Factory 方法fetchTask 正常返回 Runnable的子類的執行個體。當碰到END或檔案結束,則throw StopSignal,這樣程式就會終止。

以下是組裝 Supervisor 並執行的程式碼片段。完整的例子見:spider_task_factory.php

//如果沒有從參數指定輸入,把spider_task_factory_data.txt作為資料來源$input = isset($argv[1]) ? $argv[1] : __DIR__.'/spider_task_factory_data.txt';$spiderTaskFactory = new SpiderTaskFactory($input);$config = [    //指定taskFactory對象和Factory 方法    'factoryMethod'=>[$spiderTaskFactory, 'fetchTask'],    //指定最大並發數量為3    'quantity' => 3,];//啟動Supervisorqpm\supervisor\Supervisor::taskFactoryMode($config)->start();

SpiderTaskFactory 的實現如下:

/** * 任務工廠,必須實現 fetchTask方法。 * 該方法正常返回 * */class SpiderTaskFactory {private $_fh;public function __construct($input) {    $this->_input = $input;    $this->_fh = fopen($input, 'r');    if ($this->_fh === false) {        throw new Exception('fopen failed:'.$input);    }}public function fetchTask() {    while (true) {        if (feof($this->_fh)) {            throw new qpm\supervisor\StopSignal();        }        $line = trim(fgets($this->_fh));        if ($line == 'END') {            throw new qpm\supervisor\StopSignal();        }        if (empty($line)) {            continue;        }        break;    }    return new SpiderTask($line);}}

SpiderTask 的實現如下:

/** * 在子進程中執行任務的類 * 必須實現 qpm\process\Runnable 介面 */class SpiderTask implements qpm\process\Runnable {private $_target;public function __construct($target) {    $this->_target = $target;}//在子進程中執行的部分public function run() {    $r = @file_get_contents($this->_target);    if ($r===false) {        throw new Exception('fail to crawl url:'.$this->_target);    }    file_put_contents($this->getLocalFilename(), $r);   }private function getLocalFilename() {    $filename = str_replace('/', '~', $this->_target);    $filename = str_replace(':', '_', $filename);    $filename = $filename.'-'.date('YmdHis');    return __DIR__.'/_spider/'.$filename.'.html';}}

真實的生產環境,用隊列替換檔案輸入,即可實現持久啟動並執行生產者/消費者模型的程式。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.