1.安装gearman
cd /usr/local/src/ wget https://launchpad.net/gearmand/trunk/0.33/+download/gearmand-0.33.tar.gz tar xzvf gearmand-0.33.tar.gz cd gearmand-0.33 ./configure make make install
安装过程如果出现:configure: error: Unable to find libevent,需要yum install libevent-devel之后重试即可!
如果出现:libgearman/add.cc:53:23: error: uuid/uuid.h: No such file or directory 和libgearman/.libs/libgearman.so: undefined reference to `uuid_generate' 错误, 需要葱这里 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重试即可!
2.gearman的原理:Gearman最初在LiveJournal用于图片resize功能,由于图片resize需要消耗大量计算资源,因此需要调度到后端多台服务器执行,完成任务之后返回前端再呈现到界面。Gearman分布式任务实现原理上只用到2个字段,function name和data。function name即任务名称,由client传给job server, job server根据function name选择合适的worker节点来执行。
3.简单测试gearman,参考http://gearman.org/index.php?id=getting_started
3.1启动gearman的server,gearman运行时必须,否则报connetion错误。
gearmand -d
3.2启动worker
gearman -w -f wc -- wc -l
-w 代表启动的是worker,-f wc 代表启动一个task名字为wc, -- wc -l表示这个task是做wc -l 统计行数。
3.3在另外一个终端启动client
gearman -f wc < /etc/passwd
表示调用名字为wc的worker,参数为/etc/passwd,意思让worker统计/etc/passwd文件的行数。
4.gearman的python客户端
wget http://pypi.python.org/packages/source/g/gearman/gearman-2.0.2.tar.gz#md5=3847f15b763dc680bc672a610b77c7a7 tar xvzf gearman-2.0.2.tar.gz python setup.py install
worker.py
import os import gearman import math class CustomGearmanWorker(gearman.GearmanWorker): def on_job_execute(self, current_job): print "Job started" return super(CustomGearmanWorker, self).on_job_execute(current_job) def task_callback(gearman_worker, job): print job.data return job.data new_worker = CustomGearmanWorker(['192.168.0.181:4730']) new_worker.register_task("echo", task_callback) new_worker.work()
client.py
from gearman import GearmanClient new_client = GearmanClient(['192.168.0.181:4730']) current_request = new_client.submit_job('echo', 'foo') new_result = current_request.result print new_result
注:我的本机IP是192.168.0.181,gearman server端默认开启端口4730
启动worker:
[root@centos-181 demo]# python worker.py Job started foo
启动client,在另外一个终端
[root@centos-181 demo]# python client.py foo
参考:
http://pypi.python.org/pypi/gearman/
http://timyang.net/linux/gearman-monitor/
http://blog.csdn.net/robby213/article/details/6437739