gearman消息发送示例

来源:互联网 发布:js执行按钮点击事件 编辑:程序博客网 时间:2024/04/30 10:20

Gearman介绍

Gearman提供了一种通用的程序框架来将你的任务分发到不同的机器或者不同的进程当中。它提供了你进行并行工作的能力、负载均衡处理的能力,以及在不同程序语言之间沟通的能力。Gearman能够应用的领域非常广泛,从高可用的网站到数据库的复制任务。总之,Gearman就是负责分发处理的中枢系统,它的优点包括:

     开源:Gearman免费并且开源而且有一个非常活跃的开源社区,如果你想来做一些贡献,请点击 。

     多语言支持:Gearman支持的语言种类非常丰富。让我们能够用一种语言来编写Worker程序,但是用另外一种语言编写Client程序。

     灵活:不必拘泥于固定的形式。您可以采用你希望的任何形式,例如 Map/Reduce。

     快速:Gearman的协议非常简单,并且有一个用C语言实现的,经过优化的服务器,保证应用的负载在非常低的水平。

     可植入:因为Gearman非常小巧、灵活。因此您可以将他置入到现有的任何系统中。

     没有单点:Gearman不仅可以帮助扩展系统,同样可以避免系统的失败。

Gearman的工作原理


使用Gearman的应用通常有三部分组成:一个Client、一个Worker、一个 任务服务器。 Client的作用是提出一个 Job 任务 交给 Job Server 任务服务器。Job Server 会去寻找一个 合适的 Worker 来完成这项任务。Worker 执行由 Client 发送过来的 Job,并且将结果通过 Job Server 返回给 Client。Gearman 提供了 Client 和 Worker 的 API,利用这些API 应用可以同 Gearman Job Server来进行通信。Gearman 内部 Client 和 Worker 之间的通信都是通过 TCP 连接来进行的。工作的流程如下图所示:



示例

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     if __name__ == '__main__':    new_worker = CustomGearmanWorker(['localhost:4730'])       new_worker.register_task("echo", task_callback)       new_worker.work()  

client.py

from gearman import GearmanClientnew_client = GearmanClient(['localhost:4730'])current_request = new_client.submit_job('echo', 'foo')new_result = current_request.resultprint new_result

运行gearman server:

gearmand  --daemon  --listen=127.0.0.1

启动worker程序:python worker.py
启动client程序:python client.py

0 0
原创粉丝点击