如何在PHP应用程序中使用Net_Gearman?

时间:2013-08-17 08:58:12

标签: php gearman

我有一个PHP应用程序,我想在其中使用Gearman来完成耗时的任务。我搜索了很多,发现Net_Gearman是包含客户端和工作类的PHP API。

为了使用Net_Gearman,我该怎么办?我不了解Linux和Perl。

1 个答案:

答案 0 :(得分:4)

偶然让你上路(我使用了https://github.com/lenn0x/net_gearman中的一些笔记以及我对Gearman如何工作的知识)

客户端:

创建一个客户端脚本,该脚本将连接到您的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
  • 如果Gearman正在运行,那么您应该看到该过程如上所述运行。如果不是,你需要启动它... Ubuntu:service gearman-job-server start Centos / Redhat:service gearmand start
  • 查看队列中的作业!运行以下命令:

    (echo status ; sleep 1) | nc 127.0.0.1 4730
    

这假设您的gearmand服务器在同一台计算机上运行,​​并且您已安装netcat

相关问题