通常,Gearman被用来分发任务,以便实现异步操作。下面捋捋如何管理Gearman。

 

说明:请自行安装好Gearman和PHP PECL Gearman。

准备

我们先来创建一个Worker,实现一个简单的显示功能:

<?php

$worker= new GearmanWorker();

$worker->addServer('127.0.0.1', '4730');

$worker->addFunction('echo', 'my_echo_function');

while ($worker->work());

function my_echo_function($job) {
    return $job->workload();
}

?>

然后我们运行它:

shell> php /path/to/worker/file

可能你已经注意到,代码里有一个死循环,是不是需要Sleep一下?让我们监测看看:

shell> strace -r php /path/to/worker/file
0.000099 poll([{fd=3, events=POLLIN}], 1, 10000) = 0 (Timeout)
10.006522 write(3, "\0REQ\0\0\0\t\0\0\0\0", 12) = 12

可见PHP PECL Gearman内部已经做了休息十秒的设置,我们就不用杞人忧天了。

接下来我们以Shell为Client来调用一下:

shell> gearman -f echo "hello, world."

到这里,准备工作基本就齐活儿了,相信大家已经对Gearman有了一个初步的认识。

管理

出于效率的考虑,我们往往会启动很多个Worker,但具体应该启动多少个呢?十个还是一百个?少了不够,多了浪费,到底应该如何度量呢?

其实Gearman本身已经提供了相应的命令供我们查看状态:

shell> (echo status; sleep 0.1) | nc 127.0.0.1 4730

命令的结果会分为四列,它们的含义从左到右依次是:

  1. Function name: A string denoting the name of the function of the job
  2. Number in queue: A positive integer indicating the total number of jobs for this function in the queue. This includes currently running ones as well (next column)
  3. Number of jobs running: A positive integer showing how many jobs of this function are currently running
  4. Number of capable workers: A positive integer denoting the maximum possible count of workers that could be doing this job. Though they may not all be working on it due to other tasks holding them busy.

从这些信息可以推断出:如果系统比较繁忙的话,Number of jobs running的数值会接近Number of capable workers;Number in queue可能会大于Number of capable workers。此时我们应该增加Worker的数量,反之则应该考虑减少Worker的数量。

另外,推荐大家结合使用watch命令来监控Gearman的状态,这样更直观一些:

shell> watch -n 1 "(echo status; sleep 0.1) | nc 127.0.0.1 4730"

实际应用中,还有很多特殊情况需要考虑,比如说:程序代码更新后,如何避免手动重启Worker?还需要注意的是Worker长时间运行,一旦意外中断或者内存泄漏怎么办?通常这类进程控制问题用Supervisor都可以轻松搞定,有兴趣的读者自己看看吧。此外网络上还有一些不错的工具可以玩玩,比如:GearmanManagerGearman-Monitor

posted on 2013-10-11 17:14  sidesky  阅读(226)  评论(0编辑  收藏  举报