1.首先,確保你已經安裝了gearmand環境並且語言綁定(language binding)已經生效。
2.涉及到的各個部分:
Server The server, gearmand, will coordinate clients and workers ensuring that calls from the clients are delivered to workers and that results from workers are sent back to the client. gearmand作為我們的服務端,使client和worker協同工作,確保從client端發過來的請求能夠傳送到worker,同時使經過worker處理過的請求結果能夠返回給client。 Client A process which has a blob of data to process, a known function which can process it, and a desire to get the processed results back. In our case, the client wants a string reversed. Client就是一個有很多待處理資料的進程,它能夠被其他程式處理並得到處理後的返回結果。在我們的例子中,client端的需求是使一個字串翻轉。 Worker A process which connected to the server and offers to process function calls. In this example, the client can reverse strings. Worker是一個串連到server的進程,server端接收到client的請求後,把任務指派給worker,worker對請求作出處理。在我們的例子中,worker要做的任務是翻轉一份字串。
3.client.php(本文使用PHP作為用戶端):
<?php// Create our client object$client = new GearmanClient();// Add a server$client->addServer(); // by default host/port will be "localhost" & 4730echo "Sending job\n";// Send reverse job$result = $client->doNormal("reverse", "Hello!");if ($result) { echo "Success: $result\n";}
4.worker.py(本文使用Python作為worker):
import gearmangm_worker = gearman.GearmanWorker(['localhost:4730'])def task_listener_reverse(gearman_worker, gearman_job): print 'Reversing string: ' + gearman_job.data return gearman_job.data[::-1]# gm_worker.set_client_id is optionalgm_worker.set_client_id('python-worker')gm_worker.register_task('reverse', task_listener_reverse)# Enter our work loop and call gm_worker.after_poll() after each time we timeout/see socket activitygm_worker.work()
5.測試:
測試環境配置:
Linux3.5.7-gentoo #1 x86_64 Intel(R) Xeon(R) CPU E5645 @ 2.40GHz GenuineIntel GNU/Linux
因為我在gentoo server下面,沒法開兩個terminal,所以,要先把worker.py作為後台進程運行:
然後,用php CLI運行client.php:
可以看到,在gearman的協調下,worker完成一次client的請求。
6.英文出處:http://gearman.org/examples/reverse/
7.【更新】
上面的例子講的是同步機制,這還體現不出gearman的強大,下面是doBackground()的非同步機制:
http://gearman.org/examples/send-emails/