gearman安裝及初次使用


 

官網:  http://gearman.org/

一篇文章:

利用Gearman實現異步任務處理

一、問題分析

問題:在性能測試過程中,發現用戶管理平台在進行圖片上傳時,性能不佳。

分析:經過代碼分析得知,主要的瓶頸是圖片上傳后,還需要根據圖片組件所在頁面模塊容器進行一系列處理:圖片生成縮略圖,裁剪圖片,加水印等,這些處理在高並發的情況下,會消耗大量cpu資源,導致系統響應速度非常慢。

舊的處理方式:

次控端調用前台接口進行上傳圖片后,前台程序先上傳圖片,接着,進行圖片壓縮等處理,然后再返回結果給次控端。

整個過程是串行的,次控端需要等待前台的結果后,再顯示給用戶。這個過程存在時間浪費,圖片的處理可以提交到后台再進行處理,不需要馬上處理。

因此,考慮采用Gearman進行異步任務處理。

新的處理方式:

次控端調用前台接口上傳圖片,前台保存要上傳的圖片后,提前返回信息給次控端,接着,調用Gearman增加一個任務,然后,由Gearman自動指派任務給服務器進行任務處理。采用新的處理方式后,次控端操作體驗更加快捷。

二、Gearman詳細介紹

簡介:

官網:http://gearman.org/

Gearman是一個分布式的程序框架。Gearman提供了一個通用的應用程序,可以工作在更加適合處理這項任務的其他計算機或其他處理器上。它允許並行處理,載入平衡處理,而且可以在不同語言間進行調用。它可以應用於各種各樣的應用場合。換句話說,它是一個進行分布式處理的強健系統。以下是關於Gearman的一些長處:

l  開源:完全開源,免費的。

l  多語言:有許多語言接口,而且支持的語言數量一直在增加。

l  靈活:不依賴於任何特定的設計。

l  快速:簡單的協議和接口,可以減少現有應用程序的開銷。

l  嵌入:輕量,可以以最小的代價引入到現有程序。

l  沒有單點故障:具有較強的容錯性。

框架:

 

(摘自官網)

Gearman Client:提供客戶端調用,API可以是多種語言,目前在智能建站里應用的是PHP語言

Gearman Job Server:調度者,負責把來自客戶端的請求分發到不同服務器或不同處理器上的Worker。

Gearman Worker:負責任務處理,並返回結果。

說明:應用程序通過Client API調用創建客戶端請求,Job Server把請求分發到不同的worker上進行處理,Worker接收到請求並進行處理后返回結果。

以下是Gearman中三個基本模塊的調用關系圖:

 

 

(摘自官網)

Client與Worker是可以由不同的語言來寫的,例如:Client由PHP來寫,Worker由C語言來寫。這樣就可以很方便地把不同的語言編寫的接口進行各自的接口封裝。

不管是把Worker放到單獨服務器,還是放到集群服務器,Worker都可以正常運行。

Client發送任務到Job Server中,由Job Server負責調度,Job Server會自動檢測空閑的Worker,並發送任務到這個空閑的Worker,Worker進行任務處理。因此,Gearman框架可以實現資源負載平衡。

Gearman框架具有很強的擴展性。這個框架支持多核心CPU。如果Worker所在的服務器太繁忙,可以把服務器的CPU換成更多核心的CPU,如16核CPU,這樣就可以在這台服務器上創建16個Worker實例來進行處理。當然,Gearman也支持服務器的擴展,可以很方便地擴展出更多的Worker服務器來處理請求。唯一需要做的事情就是:啟動新服務器,安裝好Worker程序,並修改配置即可。

如果服務器掛掉了,Gearman會如何處理呢?我們可以同時運行多個Job Server,Client和Worker連接到配置好的Job Server。如果這台Job Server出現故障,則配置到這台的Client和Worker會自動連接到另外一台可用的Job Server。這里建議大家,至少要有兩台以上的Job Server,利用冗余來提高系統的容錯性。

 

安裝:

Job Server (gearmand)

gearmand (C)

A job server written in C/C++ under the BSD license that contains all of the latest protocol additions. Development for this is very active, with threading, persistent queues, and pluggable protocols now supported. Replication and better statistics reporting are coming soon. This installs an executable calledgearmand (usually in /usr/local/sbin). The C library, libgearman, is bundled in the same package.

  • The latest version can be found on Launchpad.

./configure --prefix=/opt

安裝報錯:

checking whether the Boost::Program_Options library is available... yes
configure: error: Could not find a version of the library!

 安裝boost:

  1. yum install boost  
  2. yum install boost-devel 

 

 

configure: error: could not find gperf

 安裝之:yum install  gperf

(apt-get install gperf

Linux下生成hash函數代碼的工具。)

configure: error: Unable to find libuuid

 還是錯誤。

 

因此,只有去官網下載:

http://sourceforge.net/projects/libuuid/

用源碼安裝方式安裝。

然后,再次重新執行gearman目錄下的./configure。呼呼~~~~~,終於不再出錯了,這次順利執行完畢。

 (可以加參數,如:./configure --with-sqlite3=/usr/local/sqlite3    --with-boost=/usr/local/boost-1.57   --with-boost-libdir=/usr/local/boost-1.57/lib  

--with-memcached=[PATH]
absolute path to memcached executable

 

(如果報錯libcurl

安裝:

aptitude install libcurl4-openssl-dev

 

報錯uuid錯誤:

libgearman/.libs/libgearman.so: undefined reference to `uuid_generate_time_safe@UUID_2.20'
libgearman/.libs/libgearman.so: undefined reference to `uuid_unparse@UUID_1.0'
collect2: error: ld returned 1 exit status
make[1]: *** [t/sqlite] Error 1\

 

需要蔥這里 http://sourceforge.net/projects/e2fsprogs/files/e2fsprogs/v1.42.5/ 下載並安裝e2fsprogs, 注意configure的參數必須是:./configure --prefix=/usr/local/e2fsprogs --enable-elf-shlibs,然后把uuid目錄拷過去 cp -r lib/uuid/    /usr/include/ 和 cp -rf lib/libuuid.so* /usr/lib 之后make clean重試即可!  

.安裝e2fsprogs (必須用源碼安裝,yum安裝的不好使)ubuntu好像不行。

    ./configure –enable-elf-shlibs

    make

    make install

    cp -r lib/uuid/ /usr/include/

    cp -rf lib/libuuid.so* /usr/lib

)

安裝 gearmand 后,構建 PHP 擴展。您可以從 PECL 獲取這個 tarball,也可以從 Github 復制該存儲庫。

$ wget http://pecl.php.net/get/gearman-0.6.0.tgz
$ cd pecl-gearman
#
# or
#
$ git clone git://github.com/php/pecl-gearman.git
$ cd pecl-gearman

 

有了這些代碼后,就可以開始構建擴展了:

$ phpize
$ ./configure
$ make
$ sudo make install

 ./configure 后面可以設置php-config路徑:

./configure --prefix=/opt --with-php-config=/usr/local/php/bin/php-config

 

http://ju.outofmemory.cn/entry/105792

還是報錯:

configure: error: Please install libgearman

我們在安裝gearman的時候,已經有libgearman了,但是在編譯擴展的時候,卻用額外安裝的lib,在運行的時候,難免出現性能方面的問題

在./configure的時候指定下gearman的路徑就是了,不必降低額外安裝libgearman及降低版本(http://blog.csdn.net/aidenliu/article/details/7406390

./configure --prefix=/opt --with-php-config=/usr/local/php/bin/php-config --with-gearman=/opt/gearmand/

 ( 安裝php擴展的時候,缺少 libgearman ,這在安裝gearman的時候應該已經安裝好了,在安裝gearman的時候./configure 不要加參數即可)

這個 Gearman 守護程序通常被安裝在 /usr/sbin。可以從命令行直接啟動此守護程序,也可以將這個守護程序添加到啟動配置中,以便在機器每次重啟時就可以啟動這個守護程序。

接下來,需要安裝 Gearman 擴展。打開 php.ini 文件(可以通過 php --ini 命令快速找到這個文件),然后添加代碼行 extension = gearman.so

$ php --ini
Loaded Configuration File: /etc/php/php.ini
$ vi /etc/php/php.ini
...
extension = gearman.so

 

保存此文件。要想驗證擴展是否啟用,請運行 php --info,然后查找 Gearman:

$ php --info | grep "gearman support"
gearman
gearman support => enabled
libgearman version => 0.10

 

此外,還可以用一個 PHP 代碼片段來驗證構建和安裝是否得當。將這個小應用程序保存到 verify_gearman.php:

<?php
print gearman_version() . "\n";
?>

接下來,從命令行運行此程序:

$ php verify_gearman.php
0.10

如果這個版本號與之前構建和安裝的 Gearman 庫的版本號相匹配,那么系統就已准備好了。

 

運行 Gearman

我們前面提到過,一個 Gearman 配置有三個角色:

  • 一個或多個 producer 生成工作請求。每個工作請求命名它所想要的函數,例如 email_all 或analyze
  • 一個或多個 consumer 完成請求。每個 consumer 命名它所提供的一個或多個函數並向 agent 注冊這些功能。一個 consumer 也可以被稱為是一個 worker
  • 代理對與之建立連接的那些 consumer 提供的所有服務進行集中編制。它將 producer 與恰當的 consumer 聯系起來。

借助如下的命令行,可以立即體驗 Gearman:

  1. 啟動這個 agent,即 Gearman 守護程序:
    $ sudo /usr/sbin/gearmand --daemon
  2. 用命令行實用工具 gearman 運行一個 worker。這個 worker 需要一個名字並能運行任何命令行實用工具。例如,可以創建一個 worker 來列出某個目錄的內容。-f 參數命名了該 worker 所提供的函數:
    $ gearman -w -f ls -- ls -lh
  3. 最后的一個代碼塊是一個 producer,或用來生成查找請求的一個作業。也可以用 gearman 生成一個請求。同樣,用 -f 選項來指定想要從中獲得幫助的那個服務:
  1. $ gearman -f ls < /dev/null
    drwxr-xr-x@ 43 supergiantrobot staff 1.4K Nov 15 15:07 gearman-0.6.0
    -rw-r--r--@ 1 supergiantrobot staff 29K Oct 1 04:44 gearman-0.6.0.tgz
    -rw-r--r--@ 1 supergiantrobot staff 5.8K Nov 15 15:32 gearman.html
    drwxr-xr-x@ 32 supergiantrobot staff 1.1K Nov 15 14:04 gearmand-0.10
    -rw-r--r--@ 1 supergiantrobot staff 5.3K Jan 1 1970 package.xml
    drwxr-xr-x 47 supergiantrobot staff 1.6K Nov 15 14:45 pecl-gearman

從 PHP 使用 Gearman

從 PHP 使用 Gearman 類似於之前的示例,惟一的區別在於這里是在 PHP 內創建 producer 和 consumer。每個 consumer 的工作均封裝在一個或多個 PHP 函數內。

清 單 1 給出了用 PHP 編寫的一個 Gearman worker。將這些代碼保存在一個名為 worker.php 的文件中。

1.Worker.php

<?php
  $worker= new GearmanWorker();
  $worker->addServer();
  $worker->addFunction("title", "title_function");
  while ($worker->work());
   
  function title_function($job)
  {
    return ucwords(strtolower($job->workload()));
  }
?>

清 單 2 給出了用 PHP 編寫的一個 producer,或 client。將此代碼保存在一個名為 client.php 的文件內。


清單 2. Client.php

<?php
  $client= new GearmanClient();
  $client->addServer();
  print $client->do("title", "AlL THE World's a sTagE");
  print "\n";
?>

[root@localhost code]# php Client.php
PHP Deprecated: GearmanClient::do(): Use GearmanClient::doNormal() in /opt/code/Client.php on line 4
All The Worlds's A Stags

把上面do改成doNormal

 

現在,可以用如下的命令行連接客戶機與 worker 了:

$ php worker.php &
$ php client.php
All The World's A Stage
$ jobs
[3]+ Running php worker.php &

 

這個 worker 應用程序繼續運行,准備好服務另一個客戶機。

 

這個 worker 應用程序繼續運行,准備好服務另一個客戶機。

Gearman 的高級特性

在一個 Web 應用程序內可能有許多地方都會用到 Gearman。可以導入大量數據、發送許多電子郵件、編碼視頻文件、挖據數據並構建一個中央日志設施 — 所有這些均不會影響站點的體驗和響應性。可以並行地處理數據。而且,由於 Gearman 協議是獨立於語言和平台的,所以您可以在解決方案中混合編程語言。比如,可以用 PHP 編寫一個 producer,用 C、Ruby 或其他任何支持 Gearman 庫的語言編寫 worker。

一個連接客戶機和 worker 的 Gearman 網絡實際上可以使用任何您能想象得到的結構。很多配置能夠運行多個代理並將 worker 分配到許多機器上。負載均衡是隱式的:每個可操作的可用 worker(可能是每個 worker 主機具有多個 worker)從隊列中拉出作業。一個作業能夠同步或異步運行並具有優先級。

Gearman 的最新版本已經將系統特性擴展到了包含持久的作業隊列和用一個新協議來通過 HTTP 提交工作請求。對於前者,Gearman 工作隊列保存在內存並在一個關系型數據庫內存有備份。這樣一來,如果 Gearman 守護程序故障,它就可以在重啟后重新創建這個工作隊列。另一個最新的改良通過一個 memcached 集群增加隊列持久性。memcached 存儲也依賴於內存,但被分散於幾個機器以避免單點故障。

Gearman 是一個剛剛起步卻很有實力的工作分發系統。據 Gearman 的作者 Eric Day 介紹,Yahoo! 在 60 或更多的服務器上使用 Gearman 每天處理 600 萬個作業。新聞聚合器 Digg 也已構建了一個相同規模的 Gearman 網絡,每天可處理 400,000 個作業。Gearman 的一個出色例子可以在 Narada 這個開源搜索引擎(參見 參 考資料)中找到。

Gearman 的未來版本將收集並報告統計數據、提供高級監視和緩存作業結果等。為了跟蹤這個 Gearman 項目,可以訂閱它的 Google 組,或訪問 Freenode 上它的 IRC 頻道 #gearman

 

http://www.oschina.net/question/12_7687

安裝參考:

http://blog.chinaunix.net/uid-27177626-id-4325909.html

 一篇文章:

PHP利用Gearman實現異步/並行多進程處理數據http://www.zrwm.com/?p=888

Gearman工作原理

Gearman是一個可進行任務調度分發,提供並行數據處理的分布式計算框架,支持多種編程語言.
它由三部分組成:

    • Client(客戶端)
      發出任務處理請求.比如通過一個PHP腳本.
    • Job服務器
      接收來自客戶端的任務處理請求,然后以負載均衡的方式分發給注冊的worker.
    • Worker(worker進程)
      處理Job服務器分發過來的任務處理請求,可以是一個或多個PHP腳本.

 

 

    • Gearman的一些使用場景:

      • 長時間運行的處理:圖片處理,訂單處理,批量郵件/通知 ...
      • 要求高CPU或內存的處理:大容量的數據處理,MapReduce運算,日志聚集,視頻編碼
      • 分布式和並行的處理
      • 定時處理:增量更新,數據復制
      • 限制速率的FIFO處理
      • 分布式的系統監控任務:比如Mod-Gearman
    • PHP使用Gearman

      下面的簡單例子僅為說明PHP如何使用Gearman,不具備實際生產意義.
      一個簡單的worker:

[root@centos192 worker]# cat myworker.php 
<?php

$worker = new GearmanWorker();

$worker->addServer('192.168.1.192', 4730);

$worker->addFunction('sayhello', function(GearmanJob $job){
    $name = $job->workload();
    return "hello, " . $name;
});

$worker->addFunction('logMsg', function(GearmanJob $job){
    $msg = $job->workload();
    file_put_contents(__DIR__ . '/Msg.log', $msg, FILE_APPEND);
});

while ($worker->work()){
    usleep(50000);
}

以守護進程方式啟動worker:

# nohup php myworker.php >/dev/null 2>&1 &

addFuntion另外方式:
$gmworker->addFunction("reverse", "reverse_fn");

function reverse_fn($job)
{
  return strrev($job->workload());
}

一個發送任務處理請求的client:

[root@centos191 client]# cat myclient.php 
<?php

$name = $argv[1];
if (empty($name)) {
    echo "Usage: $argv[0] {name}";
    exit(1);
}
try {
    $client = new GearmanClient();
    $client->addServer('192.168.1.192', 4730);
} catch(Exception $e){
    echo "oops", $e->getMessage();
    exit(1);
}
// 同步處理(Blocking),返回直接的處理結果
$result = $client->doNormal('sayhello', $name);
echo $result . PHP_EOL;

// 異步處理(Non-Blocking),僅返回一個處理狀態的句柄
$job_handle = $client->doBackground('logMsg', $name);
echo $job_handle . PHP_EOL;

運行myclient.php:

[root@centos191 client]# php myclient.php "Jose"
hello, Jose
H:centos192:5
http://php.net/manual/zh/gearmanclient.donormal.php
GearmanClient::doNormal — Run a single task and return a result

public string GearmanClient::doNormal ( string $function_name , string $workload [, string$unique ] )

function_name

由程序自動執行的已注冊函數。

workload

被處理的序列化數據。

unique

用於標識特定任務的唯一性 ID。

一個發出並行處理任務請求的例子tasksclient:

[root@centos191 client]# cat tasksclient.php 
<php

try {
    $client = new GearmanClient();
    $client->addServer('192.168.1.192', 4730);
} catch(Exception $e){
    echo "oops", $e->getMessage();
    exit(1);
}

$client->setCompleteCallback(function(GearmanTask $task){
    echo 'Completed task:: id :', $task->unique(), ' , handled result:', $task->data(), PHP_EOL;
});

$client->addTask('sayhello', 'Jose', null, 1);
$client->addTask('sayhello', 'John', null, 2);
$client->addTaskBackground('logMsg', 'Peter');

$client->runTasks();

運行tasksclient:

[root@centos191 client]# php tasksclient.php 
Completed task:: id :2 , handled result:hello, John
Completed task:: id :1 , handled result:hello, Jose
我最開始沒有修改addServer的ip,導致php taskslinet.php一直處於運行狀態,沒有結果輸出。這說明只要不返回結果,程序一直運行。
查看worker及隊列情況

查查當前注冊的worker及function(顯示格式:FD IP-ADDRESS CLIENT-ID : FUNCTION ...)

[root@centos192 worker]# (echo "workers"; sleep 0.1) | nc 127.0.0.1 4730
32 192.168.1.192 - : sayhello logMsg
33 127.0.0.1 - :
.

查看當前隊列情況(顯示格式FUNCTION\tTOTAL\tRUNNING\tAVAILABLE_WORKERS):

[root@centos192 worker]# (echo "status"; sleep 0.1) | nc 127.0.0.1 4730
sayhello	0	0	1
logMsg	0	0	1
.

第一列是function名稱,第2列顯示隊列中的任務數,第3列顯示正在運行的任務數,第四列顯示可用的worker數.

  • 關於Worker守護進程的啟動和監控

    上面例子中直接啟動worker腳本作為守護進程,無法監控到worker進程是否存活.
    使用Unix進程監控supervisord則可輕松解決這個問題.
    將如下配置添加到supervisord的配置中,即可實現由supervisord來啟動和監控myworker.

    [program:myworker]
    command=/usr/local/php5415/bin/php myworker.php
    process_name=%(program_name)s_%(process_num)02d
    ;修改numprocs即可同時開啟多個worker進程
    numprocs=1 
    directory=/data/www/gearman/worker
    autostart=true
    autorestart=true
    user=gearmand
    stopsignal=KILL

轉自:http://www.zrwm.com/?p=888

 

gearman安裝后在bin目錄下有2個程序gearman,gearmanadmin,它用來Run Administrative commands against a server.

--help

Provice help about the program.

--create-function

Create a function from the server.

-h  [ --host ] arg (=localhost)i

Connect to the host

-p  [ --port ] arg (=4730)

Port number or service to use for connection

--drop-function

Drop a function from the server.

--server-version

Fetch the version number for the server.

--server-verbose

Fetch the verbose setting for the server.

--status

Status for the server.

--workers

Workers for the server.

--shutdown

Shutdown server.

 

bin目錄下的gearman用來命令行操作命令。Command line client for Gearmand

 

Common options

-f  <function>

Function name to use for jobs (can give many)

-h  <host>

Job server host

-H

Print this help menu

-p  <port>

Gearman server port

-t  <timeout>

Timeout in milliseconds

-i  <pidfile>

Create a pidfile for the process

-n

In client mode run one job per line, in worker mode send data packet for each line

-N

Same as -n, but strip off the newline

Client options

-b

Run jobs in the background

-I

Run jobs as high priority

-L

Run jobs as low priority

-P

Prefix all output lines with functions names

-s

Send job without reading from standard input

-u  <unique>

Unique key to use for job

Worker options*

-c  <count>

Number of jobs for worker to run before exiting

-w

Run in worker mode

 

With gearman you can run client and worker functions from the command line.

The environmental variable GEARMAN_SERVER can be used to specify multiple gearmand servers. Please see the c:func:’gearman_client_add_servers’ for an explanation of the required syntax.

http://gearman.info/bin/gearman.html



http://gearman.info 是一個gearman文檔的網站,不錯。

http://php.net/manual/zh/gearmanclient.donormal.php php官方關於gearman的文檔。

很好的博客:http://www.livingelsewhere.net/tag/gearman/

http://www.php-oa.com/2010/09/05/perl-gearman-distributed.html

 

 

gearman實現分布式日志分析

 

編譯安裝Gearman

 

  http://blog.chinaunix.net/uid-27177626-id-4325909.html

http://www.cppblog.com/guojingjia2006/archive/2013/01/07/197076.html

http://www.2cto.com/kf/201312/262636.html

 http://www.cppblog.com/guojingjia2006/archive/2013/01/07/197076.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM