我有一个PHP应用程序,我想在其中使用Gearman来完成耗时的任务。我搜索了很多,发现Net_Gearman是包含客户端和工作类的PHP API。
为了使用Net_Gearman,我该怎么办?我不了解Linux和Perl。
答案 0 :(得分:4)
偶然让你上路(我使用了https://github.com/lenn0x/net_gearman中的一些笔记以及我对Gearman如何工作的知识)
首先,你需要确保你有装备 在你的linux机器上正确安装/运行。
Ubuntu - http://www.lornajane.net/posts/2011/installing-gearman-for-php-and-ubuntu
Centos / Redhat - 一个简单的sudo yum install gearmand libgearman
应该可以解决问题。有很多关于从源头安装的指南;你可能不想要这样做。
创建一个客户端脚本,该脚本将连接到您的gearmand进程并向其提交作业:
require_once 'Net/Gearman/Client.php';
$client = new Net_Gearman_Client('localhost:7003');
$client->someBackgroundJob(array(
'userid' => 5555,
'action' => 'new-comment'
));
创建一个库/另一个脚本来处理实际的工作(在本例中,someBackgroundJob):
<?php
class Net_Gearman_Job_someBackgroundJob extends Net_Gearman_Job_Common
{
public function run($args)
{
if (!isset($args['userid']) || !isset($args['action'])) {
throw new Net_Gearman_Job_Exception('Invalid/Missing arguments');
}
// Insert a record or something based on the $args
return array(); // Results are returned to Gearman, except for
// background jobs like this one.
}
}
?>
最后,您需要一名工人来处理这项工作。如果你想要的话,你可以把它变成一个每分钟运行的cron,直到没有任何工作要处理,那时它应该挂在那里直到它得到另一份工作:
<?php
require_once 'Net/Gearman/Worker.php';
$worker = new Net_Gearman_Worker('localhost:7003');
$worker->addAbility('someBackgroundJob');
$worker->beginWork();
?>
确保您的服务器上正在运行gearmand。您可以在Linux终端上运行以下命令:
[root@dev7 ~]# ps aux | grep gearman nobody
1826 0.0 0.1 406792 2236 ? Ssl Aug18 10:00 gearmand -d -u nobody -L 0.0.0.0 -p 4730 -P /var/run/gearmand/gearmand.pid -l /var/log/gearman/log root 4320 0.0 0.0 103240 944 pts/2 R+ 16:16 0:00 grep --color=auto gearman
service gearman-job-server start
Centos / Redhat:service gearmand start
查看队列中的作业!运行以下命令:
(echo status ; sleep 1) | nc 127.0.0.1 4730
这假设您的gearmand服务器在同一台计算机上运行,并且您已安装netcat
。