gearman和python客户端的安装和使用

来源:互联网 发布:python flask web开发 编辑:程序博客网 时间:2024/06/03 03:18

http://willvvv.iteye.com/blog/1580181


1.安装gearman

Shell代码  收藏代码
  1. cd /usr/local/src/  
  2. wget https://launchpad.net/gearmand/trunk/0.33/+download/gearmand-0.33.tar.gz  
  3. tar xzvf gearmand-0.33.tar.gz  
  4. cd gearmand-0.33  
  5. ./configure  
  6. make  
  7. 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错误。

Shell代码  收藏代码
  1. gearmand -d  

 

    3.2启动worker

Shell代码  收藏代码
  1. gearman -w -f wc -- wc -l  

    -w 代表启动的是worker,-f wc 代表启动一个task名字为wc, -- wc -l表示这个task是做wc -l 统计行数。

 

    3.3在另外一个终端启动client

Shell代码  收藏代码
  1. gearman -f wc < /etc/passwd  

    表示调用名字为wc的worker,参数为/etc/passwd,意思让worker统计/etc/passwd文件的行数。

 

4.gearman的python客户端

 

Shell代码  收藏代码
  1. wget http://pypi.python.org/packages/source/g/gearman/gearman-2.0.2.tar.gz#md5=3847f15b763dc680bc672a610b77c7a7  
  2. tar xvzf  gearman-2.0.2.tar.gz  
  3. python setup.py install  

 

worker.py

Python代码  收藏代码
  1. import os  
  2. import gearman  
  3. import math  
  4.   
  5. class CustomGearmanWorker(gearman.GearmanWorker):    
  6.     def on_job_execute(self, current_job):    
  7.         print "Job started"   
  8.         return super(CustomGearmanWorker, self).on_job_execute(current_job)    
  9.    
  10. def task_callback(gearman_worker, job):    
  11.     print job.data   
  12.     return job.data  
  13.    
  14. new_worker = CustomGearmanWorker(['192.168.0.181:4730'])    
  15. new_worker.register_task("echo", task_callback)    
  16. new_worker.work()  

 

client.py

Python代码  收藏代码
  1. from gearman import GearmanClient  
  2.   
  3. new_client = GearmanClient(['192.168.0.181:4730'])  
  4. current_request = new_client.submit_job('echo''foo')  
  5. new_result = current_request.result  
  6. print new_result  

 

注:我的本机IP是192.168.0.181,gearman server端默认开启端口4730

 

启动worker:

Shell代码  收藏代码
  1. [root@centos-181 demo]# python worker.py  
  2. Job started  
  3. foo  

 

启动client,在另外一个终端

Shell代码  收藏代码
  1. [root@centos-181 demo]# python client.py   
  2. foo  
原创粉丝点击