Gearman是一个用来把工作委派给其他机器、分布式的调用更适合做某项工作的机器、并发的做某项工作在多个调用间做负载均衡、或用来在调用其它语言的函数的系统.
官方网站:http://gearman.org/
以下的操作均在ubuntu12.0下进行,其他操作系统均雷同。
1、gearman安装
安装依赖包
sudo apt-get install libboost-program-options-dev libevent-dev uuid-dev
截止笔者发表博文gearman最新稳定版本1.0..6:https://launchpad.net/gearmand/1.0/1.0.6/+download/gearmand-1.0.6.tar.gz
wget https://launchpad.net/gearmand/1.0/1.0.6/+download/gearmand-1.0.6.tar.gz tar -zxvf gearmand-1.0.6.tar.gz cd gearmand-1.0.6 ./configure --prefix=/usr/local/gearmand sudo make sudo make install
如果出现下面错误提示:
sorry, unimplemented: Graphite loop optimizations can only be used if the libcloog-ppl0 package is installed
解决办法:修改Makefile,查找并去掉 floop-parallelize-all
启动gearmand
/usr/local/gearmand/sbin/gearmand -d
如果提示log文件/usr/local/gearmand/var/log/不存在,则新建
sudo mkdir -p /usr/local/gearmand/var/log/ sudo chmod 777 /usr/local/gearmand/var
下载php的gearman扩展
wget http://pecl.php.net/get/gearman-1.0.2.tgz tar -zxvf gearman-1.0.2.tgz cd gearman-1.0.2
安装libgearman
sudo apt-get install libgearman-dev
笔者的php安装在/usr/loal/php目录下,
/usr/local/php/bin/phpize ./configure --with-php-config=/usr/local/php/bin/php-config sudo make sudo make install
在文件夹/usr/local/php/lib/php/extensions/no-debug-non-zts-20100525/下会生成gearman的so文件,编辑php.ini加载gearman.so
vim /usr/local/php/etc/php.ini
添加
extension=/usr/local/php/lib/php/extensions/no-debug-non-zts-20100525/gearman.so
笔者使用的服务器为nginx+php-fpm的模式,重启php-fpm即可
sudo kill -usr2 php-fpm-master-pid
查看phpinfo查看gearman是否加载
php -r "phpinfo();" | grep gearman安装完毕。
2、gearman的使用
下图为官网上的一张示意图,可以很好的阐述组成gearman的三部分的分工。
由上图,我们可以很容易的发现gearman是由Client+job server+worker 组成。
Client:它提供各种编程语言(C,PHP,Perl...)的API,在gearman中作为请求的发起者。
Job Server:它将根据Client发来的请求为其找到一个可以执行这个请求的worker,并接受worker的回应并回应给Client。
Worker:它提供各种编程语言(C,PHP,Perl...)的API,在gearman中作为请求的真实回应者。
下面是一个php使用gearman的例子:
Client:client.php
<?php // Create our client object $client = new GearmanClient(); // Add a server $client->addServer(); // by default host/port will be "localhost" & 4730 echo "Sending job\n"; // Send reverse job $result = $client->doNormal("reverse", "Hello!"); if ($result) { echo "Success: $result\n"; }
Worker:worker.php
<?php // Create our worker object $worker = new GearmanWorker(); // Add a server (again, same defaults apply as a worker) $worker->addServer(); // Inform the server that this worker can process "reverse" function calls $worker->addFunction("reverse", "reverse_fn"); while (1) { print "Waiting for job...\n"; $ret = $worker->work(); // work() will block execution until a job is delivered if ($worker->returnCode() != GEARMAN_SUCCESS) { break; } } // A much simple reverse function function reverse_fn(GearmanJob $job) { $workload = $job->workload(); echo "Received job: " . $job->handle() . "\n"; echo "Workload: $workload\n"; $result = strrev($workload); echo "Result: $result\n"; return $result; }
运行:
php worker.php & php client.php