Gearman一个异步任务调度器

来源:互联网 发布:屏幕录制软件免费版 编辑:程序博客网 时间:2024/06/05 16:38

Gearman是一个比较著名的任务调度器,可以将工作任务委派给后台别的进程或者别的机器的进程去做,当然对于远程过程调用我们可以有很多种选择,RPC,REST接口等都是不错的解决方案,但是Gearman提供了对各种语言丰富的集成,它的程序框架如下图,我们可以看出客户端可以由C,PHP,Perl等语言实现,Worker端也可以由自己选择一个工作语言,这种多系统多语言的集成显得非常的灵活。gearmand在两端都封装了各种语言的api,方便不同语言的程序员使用。


我们来参照官方手册试用一下吧。官方提供C,Java,Perl等三个服务器端版本的gearmand,我这里就用Perl的模块来测试。

首先下载Gearman-Server模块,解压安装,然后运行./gearmand,我的机器上提示缺少依赖包

[root@fedora Gearman-Server-1.11]# ./gearmand Can't locate Danga/Socket.pm in @INC (@INC contains: /home/fedora/Projects/Gearman-Server-1.11/lib /usr/local/lib/perl5 /usr/local/share/perl5 /usr/lib/perl5 /usr/share/perl5 /usr/local/lib/perl5/site_perl/5.10.0/i386-linux-thread-multi /usr/local/lib/perl5/site_perl/5.10.0 /usr/lib/perl5/vendor_perl/5.10.0/i386-linux-thread-multi /usr/lib/perl5/vendor_perl /usr/lib/perl5/site_perl .) at /home/fedora/Projects/Gearman-Server-1.11/lib/Gearman/Server/Client.pm line 24.BEGIN failed--compilation aborted at /home/fedora/Projects/Gearman-Server-1.11/lib/Gearman/Server/Client.pm line 24.Compilation failed in require at /home/fedora/Projects/Gearman-Server-1.11/lib/Gearman/Server.pm line 27.BEGIN failed--compilation aborted at /home/fedora/Projects/Gearman-Server-1.11/lib/Gearman/Server.pm line 27.Compilation failed in require at ./gearmand line 103.BEGIN failed--compilation aborted at ./gearmand line 103.
然后用CPAN工具安装缺失的module,cpan安装毕竟不如yum或者apt-get那么可以智能地解决依赖关系,还好我这边只需要安装下面两个库即可
cpan -i Danga/Socket.pmcpan -i Gearman/Util.pm

然后安装php的扩展(http://pecl.php.net/get/gearman-0.7.0.tgz)(yum install php-devel && phpize && ./configure && make && make install)

将gearman.so文件拷贝到php的module目录下,然后修改php.ini文件添加extension=gearman.so,编写下面两个文件

client.php

<?php$client= new GearmanClient();$client->addServer("127.0.0.1",7003);print $client->do("reverse", "Hello World!")?>

worker.php

<?php$worker= new GearmanWorker();$worker->addServer("127.0.0.1",7003);$worker->addFunction("reverse", "my_reverse_function");while ($worker->work());function my_reverse_function($job){  return strrev($job->workload());}?>

打开终端,执行./gearmand -p 7003(gearmand的使用手册参考官方文档)(-d表示守护进程方式运行,-p占用端口)

然后开启两个终端分别执行php worker.php以及php client.php可以看到

[root@fedora Gearman-Server-1.11]# php client.php !dlroW olleH[root@fedora Gearman-Server-1.11]# 
已经执行完字符串翻转了,感觉这个任务调度器很酷。我们还可以在运行第二个worker.php副本,第一个worker停止工作后,gearmand会智能地把工作转移到worker2.php上。比较好用的一个任务调度器。
原创粉丝点击