Gearman 的安裝和使用
官網地址:http://gearman.org/
介紹
Gearman是一個用來把工作委派給其他機器、分布式的調用更適合做某項工作的機器、并發(fā)的做某項工作在多個調用間做負載均衡、或用來在調用其它語言的函數的系統(tǒng)。
Gearman提供了一種通用的程序框架來將你的任務分發(fā)到不同的機器或者不同的進程當中。它提供了你進行并行工作的能力、負載均衡處理的能力,以及在不同程序語言之間溝通的能力。Gearman能夠應用的領域非常廣泛,從高可用的網站到數據庫的復制任務??傊珿earman就是負責分發(fā)處理的中樞系統(tǒng),它的優(yōu)點包括:
開源:Gearman免費并且開源而且有一個非?;钴S的開源社區(qū),如果你想來做一些貢獻,請點擊 。
多語言支持:Gearman支持的語言種類非常豐富。讓我們能夠用一種語言來編寫Worker程序,但是用另外一種語言編寫Client程序。
靈活:不必拘泥于固定的形式。您可以采用你希望的任何形式,例如 Map/Reduce。
快速:Gearman的協(xié)議非常簡單,并且有一個用C語言實現的,經過優(yōu)化的服務器,保證應用的負載在非常低的水平。
可植入:因為Gearman非常小巧、靈活。因此您可以將他置入到現有的任何系統(tǒng)中。
沒有單點:Gearman不僅可以幫助擴展系統(tǒng),同樣可以避免系統(tǒng)的失敗。
運行過程:
一個Gearman請求的處理過程涉及三個角色:Client -> Job -> Worker。
Client:請求的發(fā)起者,可以是 C,PHP,Perl,MySQL UDF 等等。
Job:請求的調度者,用來負責協(xié)調把 Client 發(fā)出的請求轉發(fā)給合適的 Work。
Worker:請求的處理者,可以是 C,PHP,Perl 等等。
因為 Client,Worker 并不限制用一樣的語言,所以有利于多語言多系統(tǒng)之間的集成。
甚至我們通過增加更多的 Worker,可以很方便的實現應用程序的分布式負載均衡架構。
Gearman的工作原理:
使用Gearman的應用通常有三部分組成:一個Client、一個Worker、一個 任務服務器。 Client的作用是提出一個 Job 任務 交給 Job Server 任務服務器。Job Server 會去尋找一個 合適的 Worker 來完成這項任務。Worker 執(zhí)行由 Client 發(fā)送過來的 Job,并且將結果通過 Job Server 返回給 Client。Gearman 提供了 Client 和 Worker 的 API,利用這些API 應用可以同 Gearman Job Server來進行通信。Gearman 內部 Client 和 Worker 之間的通信都是通過 TCP 連接來進行的。工作的流程如下圖所示:

Gearman的用處:
Gearman首先提供了一個多語言通訊的接口,當然還有比這個更簡單有效的辦法。Gearman可以將工作的負載分擔到不同的機器中,如下圖所示:

Job Server 可以開啟多個實例,這樣在其中一個發(fā)生故障的時候,可以 Failover 到其他的機器上。同時 Worker 也可以是多個實例進行運行,因為當前的服務器很多都是多核的。
安裝
yum 安裝
安裝gearmand
$ sudo yum install gearmand
安裝php擴展
$ sudo yum install --enablerepo=remi --enablerepo=remi-php56 php-pecl-gearman
查看擴展是否安裝成功
$ php -m | grep gearman
gearman
源碼安裝
安裝gearmand
$ wget https://launchpad.net/gearmand/1.2/1.1.12/+download/gearmand-1.1.12.tar.gz
$ tar xvzf gearmand-1.1.12.tar.gz
$ cd gearmand-1.1.12
$ ./configure
$ make
$ sudo make install
安裝php擴展
$ wget http://pecl.php.net/get/gearman-1.1.2.tgz
$ tar xvzf gearman-1.1.2.tgz
$ cd gearman-1.1.2
$ phpize
$ ./configure
$ make
$ make install
手動添加配置
$ php --ini //Loaded Configuration File: /etc/php/php.ini
$ vi /etc/php/php.ini
...
extension = gearman.so
使用
相關代碼:
worker.php
<?php
$worker= new GearmanWorker();
$worker->addServer("127.0.0.1", 4730);
$worker->addFunction("title", "title_function");
while ($worker->work());
function title_function($job){
return "你請求的數據:" . $job->workload() . " 請求時間:" . date('Y-m-d H:i:s');
//return ucwords(strtolower($job->workload()));
}
?>
client.php
<?php
$client= new GearmanClient();
$client->addServer("127.0.0.1", 4730);
print $client->do("title", json_encode(
[
'username'=>'jack',
'email'=>'jack@foxmail.com',
]
));
print "\n";
?>
測試:
啟動服務
$ sudo gearmand -d
啟動worker
$ php worker.php &
[1] 15135
啟動client
$ php client.php
你請求的數據:{"username":"jack","email":"jack@foxmail.com"} 請求時間:2017-07-10 23:25:30
參考:
https://segmentfault.com/a/1190000000494087
https://www.ibm.com/developerworks/cn/opensource/os-php-gearman/
http://gearman.org/getting-started/#client
http://php.net/manual/zh/book.gearman.php