2013-11-15

Gearman with PHP

為了網頁平台要多工處理多個request,這幾天看了一下Message Queue
這篇文章中將D-bus和Gearman做了一些比較
並且也有D-bus with PHP 的教學
有鑑於文末提到D-bus對PHP的支援不及Gearman成熟,就決定來試試看Gearman了

Gearman的概念圖

另在最近在slideshare上面有非常完整的教學分享,觀念非常詳細完整,這次的實作也是參考他的,我需要的系統是Asynchronous的方式
實作系統
OS:Ubuntu12.04
Worker & client:PHP 5.3.10
Gearmand 1.0.6
1.  Install Job Server
apt-get install gearman gearman-job-server libgearman-dev
pecl config-set http_proxy http://xxx.xxx.xxx:port
pecl install channel://pecl.php.net/gearman-1.1.2
echo 'extension=gearman.so' > /etc/php5/apache/conf.d/gearman.ini
vi /etc/php5/apache/php.ini
    extension = gearman.so
service apache2 restart
/etc/init.d/gearman-job-server start
   因為我的DB為MongoDB所以不安裝libdrizzle0

2.  測試gearman是否安裝完成
php -i | grep gearman
3.  Client端程式碼
addServer();
$data = array('name' => 'xxx','phone' =>'12345');
$client->doBackground('phoneBook',serialize($data));
?>
   Note:
    GearmanClient class
    addServer 表示要通知哪些Job Server
    利用doBackground方法將job丟給對應的worker,Job Server會將該工作交給Worker
    doBackground(Worker的識別,傳給Worker的資料),因為資料須為字串,如果傳array,需要用serialize將資料序列畫

4.  Worker端程式碼
addServer();
$worker->addFunction('phoneBook','doPhoneBook');
while($worker->work())
     sleep(1);
function doPhoneBook($job){
     $data = unserialize($job->workload());
     ...
     ...
     ...
}
?>
5.  執行步驟

   php Worker.php
   php Client.php

6.  在背景執行多個task
$client->runTaskBackground("function_name",data);
   reference

沒有留言: