Gearman 以 Client → Job Server → Worker 三角色解決跨語言系統整合與分散式負載均衡,輕量且無需 WebService 複雜協定。
wget https://launchpad.net/gearmand/trunk/0.8/+download/gearmand-0.8.tar.gz
tar zxf gearmand-0.8.tar.gz
cd gearmand-0.8
./configure && make && make install
wget https://pecl.php.net/get/gearman-0.4.0.tgz
tar zxf gearman-0.4.0.tgz
cd gearman-0.4.0
phpize && ./configure && make && make install
echo 'extension="gearman.so"' >> /etc/php.ini
gearmand -d # 一般用戶
gearmand -d -u root # root
# 監聽 4730 port
<?php
$worker = new GearmanWorker();
$worker->addServer('127.0.0.1', 4730);
$worker->addFunction('reverse', 'my_reverse_function');
while ($worker->work());
function my_reverse_function($job) {
return strrev($job->workload());
}
?>
php worker.php &
<?php
$client = new GearmanClient();
$client->addServer('127.0.0.1', 4730);
echo $client->do('reverse', 'Hello World!'), "\n";
?>
php client.php
# 輸出:!dlroW olleH
doBackground() 火即不管。
# 啟動 Worker(執行 wc -l)
gearman -w -f wc -- wc -l &
# 送入資料
gearman -f wc < /etc/passwd
詳細 API 請參考 Gearman 官方文件與 PDF 指南。