【Gearman學習筆記】分散式處理入門

來源:互聯網
上載者:User

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/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.