---
title: "ubuntu 安装 gearman"
author: "phpseyo"
date: "2013-10-24T16:25:43Z"
tags: []
categories: ["行业应用"]
slug: "ubuntu-gearman"
draft: false
lastmod: "2013-10-28T11:34:21Z"
id: 1963907
url: "https://phpseyo.iteye.com/blog/1963907"
---

安装过程为：  
1\. 下载  
wget http://launchpad.net/gearmand/trunk/0.26/+download/gearmand-0.26.tar.gz  
2\. 编译  
% tar -xvzf gearmand-0.26.tar.gz  
% cd gearmand  
% ./configure  
3\. 安装  
% make  
% make install  
但是在第2步的时候发现了很多编译错误：

1. configure: error: no acceptable C compiler found in $PATH  
   这是说没有装编译器，可以装个GCC或G++
2. configure: error: cannot find Boost headers version &gt;= 1.39.0

这是说没有安装boost包或库  
4\. 最后找了下，所有的依赖包:  
sudo apt-get install uuid-dev libevent-dev libboost-all-dev libdrizzle-dev

/\** 未遇到

在./configure的时候，可能会出现缺少libraries的情况：

checking for libevent… no  
configure: error: cannot find the flags to link with Boost program\_options  
configure: error: libevent is required for gearmand. On Debian this can be found in libevent-dev. On RedHat this can be found in libevent-devel.

可能系统缺少libboost、libevent和uuid等等，需要依次安装：

sudo apt-get install libboost-program-options-dev  
sudo apt-get install libevent-dev  
sudo apt-get install uuid-dev

\*/

5\. 运行./configure 之后出现下面结果：

Configuration summary for gearmand version 0.26 * Installation prefix: /usr/local * System type: pc-linux-gnu * Host CPU: i686 * C Compiler: gcc (Ubuntu/Linaro 4.4.4-14ubuntu5) 4.4.5 * Assertions enabled: yes * Debug enabled: no * Warnings as failure: * Building with libsqlite3 no * Building with libdrizzle no * Building with libmemcached no * Building with libp no * Building with tokyocabinet no/\** apt-get安装提示有如下软件包，没试过apt-get install gearman gearman-job-server gearman-server gearman-tools\*/

因为本试验Client和Worker端都由PHP来实现，所以需要安装php的gearman扩展

安装Gearman PHP extension：

wget [http://pecl.php.net/get/gearman-0.7.0.tgz](http://pecl.php.net/get/gearman-0.7.0.tgz)  
tar zxf gearman-0.7.0.tgz  
cd gearman-0.7.0  
phpize  
./configure  
sudo make  
sudo make install

中间可能遇到的问题：

出现 error "unimplemented: Graphite loop optimizations .. 错误，

则执行

 

sudo apt-get install cloog-ppl

 

找不到phpize命令，phpize在php开发包中，所以要先安装php5-dev

sudo apt-get install php5-dev

**编译时出错：configure: error: Please install libgearman，执行**

**apt-get install libgearman-dev**

安装完后，就可以在源码目录中执行phpize生成相关安装配置信息，接着执行后面的./configure等

make install后，它告诉你一个目录，生成的gearman.so就在那里。

根据需要考到相应PHP的扩展目录里（因为我直接用系统默认安装的php，它自动生成就在扩展中）

接下来修改php.ini 在其中加入

extension = “gearman.so”

————————————————————————————————————————————

然后，开始编写client和worker端

client.php

&lt;?php  
$client= new GearmanClient();  
$client-&gt;addServer(“127.0.0.1″, 4730);  
print $client-&gt;do(“title”, “Linvo”);  
print “\\n”;  
?&gt;

worker.php

 

&lt;?php  
$worker= new GearmanWorker();  
$worker-&gt;addServer(“127.0.0.1″, 4730);  
$worker-&gt;addFunction(“title”, “title\_function”);  
while ($worker-&gt;work());

function title\_function($job)  
{  
$str = $job-&gt;workload();  
return strlen($str);  
}  
?&gt;

准备工作已经完毕，试验开始

1、启动job

gearmand -d

2、启动worker

php -c /etc/php5/apache2/php.ini worker.php

3、启动client（新开终端中打开）

php -c /etc/php5/apache2/php.ini client.php

屏幕显示字符串的长度 “5”

这里，有几点需要说明一下：

1、这里直接用php cli方式运行，添加-c参数是为了加载php.ini配置文件，以加载gearman扩展

2、worker应该做成守护进程（CLI模式），可以开启多个，这样client发起的任务就会分发到各个worker分别来执行（自动负载均衡）

这个例子由于太过简单，即使开启多个worker也无法看出效果，不过可以通过终止其中一个，可以看出系统自动切换到其他worker继续正常执行

3、同理，client也是可以开启多个的（模型请参考之前的那边日志）

4、同时，job也可以开启多个，以避免单点故障

 

简易实作  
   
接下来，我们可以试着用 PHP API 来连接 Job Server 。前面安装好 PECL 的 Gearman Extension 后，我们就可以在 PHP 程式裡建立操作 Gearman API 的物件了。  
   
以下我用简单的方式来模拟 Client 和 Worker 的运作，所以这裡 Client 和 Worker 会在同一部主机上，但实际运作时是不需要的，请大家注意。  
   
Client 端程式  
&lt;?php  
$client= new GearmanClient();  
$client-&gt;addServer("127.0.0.1", 4730);  
$who = array('who\_send'=&gt;'web','get\_email'=&gt;'');  
$img\['image'] = '/var/www/pub/image/test.png';  
print $client-&gt;do("sendEmail", serialize($who));  
print "\\n";  
print $client-&gt;do("resizeImage", serialize($img));  
print "\\n";  
?&gt;  
Worker 端程式  
&lt;?php  
$worker = new GearmanWorker();  
$worker-&gt;addServer(); // 预设为 localhost  
$worker-&gt;addFunction('sendEmail', 'doSendEmail');  
$worker-&gt;addFunction('resizeImage', 'doResizeImage');  
   
while($worker-&gt;work()) {  
    sleep(1); // 无限回圈，并让 CPU 休息一下  
}  
   
function doSendEmail($job)  
{  
    $data = unserialize($job-&gt;workload());  
    print\_r($data);  
    sleep(3); // 模拟处理时间  
    echo "Email sending is done really.\\n\\n";  
}  
   
function doResizeImage($job)  
{  
    $data = unserialize($job-&gt;workload());  
    print\_r($data);  
    sleep(3); // 模拟处理时间  
    echo "Image resizing is really done.\\n\\n";  
}

 

首先， PHP Gearman Extension 提供了一个名为 GearmanClient 的类别，它可以让程式安排工作给 Job Server 。  
   
而 addServer 方法表示要通知的是哪些 Job Server ，也就是说如果有多台 Job Server 的话，就可以透过 addServer 新增。  
   
然后我们将要呼叫哪个 Worker 以及该 Worker 所需要的资料，利用 GearmanClient 的 doBackground 方法传送过去。 doBackground 方法顾名思义就是在背景执行， Client 在丢出需求后就可以继续处理其他的程式，也就是我们常说的「射后不理」。  
   
doBackground 方法的第一个参数是告诉 Job Server 要执行哪个功能，而这个功能则是由 Worker 提供的；要注意是，这个参数只是识别用的，并不是真正的函式名称。而第二个参数是要传给 Worker 的资料，它必须是个字串；因此如果要传送的是阵列的话，我们就要用 PHP 的 serialize 函式来对这些资料做序列化。  
 

 

PHP 的 Gearman Extension 也提供了一个 GearmanWorker 类别，让我们可以实作 Worker 。而 GearmanWorker 类别也提供了addServer 方法，让所生成的 Worker 物件可以注册到 Job Server 中。  
   
另外 GearmanWorker 类别也提供了 addFuncton 方法，告诉 Job Server 自己可以处理哪些工作。 addFunction 的第一个参数就是对应到 GearmanClient::doBackground 方法的第一个参数，也就是功能名称；这使得 Client 和 Worker 能透过这个名称来互相沟通。而第二个参数则是一个callback函式，它会指向真正应该要处理该工作的函式或类别方法等。  
   
最后因为 Worker 因为要随时准备服务，是不能被中断的，因此我们透过一个无限迴圈来让它常驻在 Job Server 中。  
   
测试  
   
准备好 Client 和 Worker 的程式后，就可以测试看看了。首先我们必须得先执行 worker.php ，让它开始服务。  
 

php worker.php  
   
这时我们会看到 worker.php 停驻在等待服务。  
   
接着我们开启另一个 console 视窗来执行 client.php ：  
 

切换到执行 worker.php 的 console 时，就会看到以下执行结果：  
Array  
(  
    \[who\_send] =&gt; web  
    \[get\_email] =&gt;   
)  
Email sending is really done.  
   
Array  
(  
    \[image] =&gt; /var/www/pub/image/test.png  
)  
Image resizing is really done.

 

这表示 Worker 正常地处理 Client 的需求了。  
   
现在试着把 worker.php 停掉 (Ctrl+C) ，然后再执行 client.php ，大家应该会发现 client.php 还是正常地完成它的工作；这是因为 Job Server 帮我们把需求先放在 Queue 裡，等待 Worker 启动后再处理。  
   
这时可以查看 MySQL 的 gearman 资料库，在 gearman\_queue 资料表中应该就会看到以下结果：

这表示 Job Server 成功地将 Queue 保留在 MySQL 资料表中。  
   
接着再执行 worker.php ，这时 Job Server 会得知 Worker 复活，赶紧将 Queue 裡面属于该 Worker 应该执行的工作再发送出去以完成作业；而 Worker 完成作业后， Job Server 就会把 Queue 清空了。  
   
Message Queue 这个架构的应用可以说相当广泛，尤其在大流量的网站上，我们能透过它来来有效运用分散式的系统架构，以处理更多使用者的需求。  
   
而目前 Gearman 可说是在 PHP 上一个很棒的 Message Queue 支援套件，而且 API 也相当完善；因此如果能善用 Gearman 的话，那么我们在 PHP 网站的架构上就可以有更大的延展性，也能有更多的可能性。

 

（转载自:[http://hi.baidu.com/baisiye/item/b856baea3cc4892a5a7cfbe6](http://hi.baidu.com/baisiye/item/b856baea3cc4892a5a7cfbe6)）

 

补充说明：

1\. 有个 gearadmin 的命令管理工具，可以查看gearman的运行状态等，如

![](http://dl2.iteye.com/upload/attachment/0090/6146/eb02b2d4-b988-3104-882e-bab0300c72d3.png)  
 

bb2和bb1为注册的函数名，第一列为等待执行的任务数，第二列为正在执行的任务数，第三列为对应的worker 数。

 

 2. gearmand -d 这个命令默认是使用内存存储队列的，假如需要使用持久化存储，可以结合mysql来使用。

新建数据库 gearman

新建表：

```
CREATETABLE`gearman_queue`(
`unique_key`VARCHAR(64)NOTNULL,
`function_name`VARCHAR(255)NOTNULL,
`priority`INT(11)NOTNULL,
`data`LONGBLOBNOTNULL,
`when_to_run`INT(11)NULLDEFAULTNULL,
PRIMARYKEY(`unique_key`)
)
```

使用mysql作为队列存储：

/usr/local/sbin/gearmand -L 127.0.0.1 --queue-type=mysql --mysql-host=127.0.0.1 --mysql-user=root --mysql-password=123456 --mysql-db=gearman --mysql-table=gearman\_queue -d

从上面的命令参数可以看出需要配置的mysql数据表信息。-d 参数为使用守护进程运行gearmand。

经测试，假如在gearmand有任务队列执行的情况下重启，队列会继续保存着，只是worker丢失了，需要重新注册一次worker；而假如worker重启，gearman会自动继续执行队列任务。

 

3\.