gearman的安装启动及python API使用实例

yipeiwu_com6年前Python基础

本文讲述了gearman的安装启动及python API使用实例,对于网站建设及服务器维护来说非常有用!

一、概述:

Gearman是一款非常优秀的任务分发框架,可以用于分布式计算。具体的gearmand服务的安装启动及gearman的python 模块的安装以及简单示例如下:
 
操作系统:rnel 5.7

1. 首先,我们需要安装gearmand,在centos和rhel环境下,我们只需运行以下命令:

yum install gearmand -y
 
注意:如果不希望通过yum的方式来安装gearmand,可以通过源码编译安装,具体安装方法可以参考:/post/51999.htm

安装完毕之后,就可以启动gearmand服务:

gearmand -p 4730 -L 10.22.10.90 --log-file=/tmp/gearmand-4730.log --pid-file=/tmp/gearmand-4730.pid -d

2. 安装python-gearman

gearman的python模块,下载地址为:https://pypi.python.org/pypi/gearman/2.0.2

我们可以用以下命令安装(两个命令均可,二选一):

easy_install gearman
pip install gearman

或者也可以通过源码安装:

wget https://pypi.python.org/packages/source/g/gearman/gearman-2.0.2.tar.gz --no-check-certificate
tar zxvf gearman-2.0.2.tar.gz 
cd gearman-2.0.2 
python setup.py install

这样,我们就完成了python-gearman的安装。

二、使用示例:

下面,列举一个简单的python例子:
首先,我们需要编写一个worker,代码如下:

1.文件名:echoWorker.py

#!/usr/bin/env python 
import os 
import gearman 
import math 
class MyGearmanWorker(gearman.GearmanWorker): 
  def on_job_execute(self, current_job): 
    print "Job started" 
    print "===================\n" 
    return super(MyGearmanWorker, self).on_job_execute(current_job) 
def task_callback(gearman_worker, gearman_job): 
  print gearman_job.data 
  print "-----------\n" 
  return gearman_job.data 
my_worker = MyGearmanWorker(['10.22.10.47:4730']) 
my_worker.register_task("echo", task_callback) 
my_worker.work() 

2.编写client,如下:
文件名:echoClient.py

#!/usr/bin/env python2.7 
from gearman import GearmanClient 
gearman_client = GearmanClient(['192.168.12.34:4730']) 
gearman_request = gearman_client.submit_job('echo', 'test gearman') 
result_data = gearman_request.result 
print result_data 

注意上面GearmanClient(['192.168.12.34:4730'])中的IP地址,需要根据实际启动gearmand服务的IP地址和端口号为准。
 
3.然后,我们运行以下命令:

python echoWorker.py
python echoClient.py

至此,即可看到输出。

相关文章

Sanic框架配置操作分析

本文实例讲述了Sanic框架配置操作。分享给大家供大家参考,具体如下: 简介 Sanic是一个类似Flask的Python 3.5+ Web服务器,它的写入速度非常快。除了Flask之外...

Python遍历numpy数组的实例

在用python进行图像处理时,有时需要遍历numpy数组,下面是遍历数组的方法: [rows, cols] = num.shape for i in range(rows - 1...

简介Python的collections模块中defaultdict类型的用法

defaultdict 主要用来需要对 value 做初始化的情形。对于字典来说,key 必须是 hashable,immutable,unique 的数据,而 value 可以是任意的...

python ftp 按目录结构上传下载的实现代码

具体代码如下所示: #!/usr/bin/python # coding=utf-8 from ftplib import FTP import time import os def...

python利用正则表达式排除集合中字符的功能示例

前言 我们在之前学习过通过集合枚举的功能,把所有需要出现的字符列出来,保存在集合里面,这样正则表达式就可以根据集合里的字符是否存在来判断是否匹配成功,如果在集合里,就匹配成功,否则不成功...