PHP Gearman worker从服务器检索任务。当我们没有任何新任务时,我们在后台做一些其他工作。请查看下面的实现。
$worker = new GearmanWorker();
$worker->addServer('host', 123);
$worker->addFunction('name', array($this, 'function'));
$worker->setTimeout(5000);
while ($worker->work() || GEARMAN_TIMEOUT == $worker->returnCode()) {
if (GEARMAN_TIMEOUT == $worker->returnCode()) {
$this->handleTimeout();
} elseif (GEARMAN_SUCCESS != $worker->returnCode()) {
$this->handleFail();
break;
}
}
代码看起来很简单,大多数情况下都能正常工作。但是,由于某些原因,脚本无法连接到服务器时,$worker->returnCode()
等于GEARMAN_TIMEOUT
。
$worker->returnCode()
值相同
- 当我们没有任何新任务时
- 当脚本连接到服务器失败时
当脚本连接到服务器失败时,错误信息和代码如下:
$worker->error()
gearman_worker_grab_job(GEARMAN_TIMEOUT)选项超时返回到达-> libgearman/worker.cc:869
$worker->getErrno()
0
当客户端连接到服务器失败时如何捕获错误?
我们已经添加了GearmanWorker::echo()
调用来检查Gearman服务器是否可用。
查看修改后的代码
$worker = new GearmanWorker();
$worker->addServer('host', 123);
$worker->addFunction('name', array($this, 'function'));
$worker->setTimeout(5000);
while ($worker->work() || GEARMAN_TIMEOUT == $worker->returnCode()) {
if (GEARMAN_TIMEOUT == $worker->returnCode()) {
$this->handleTimeout();
$echo = @$worker->echo(1);
if (!$echo) {
echo 'Failed to connect to Gearman Gerver.'. PHP_EOL;
break;
}
} elseif (GEARMAN_SUCCESS != $worker->returnCode()) {
$this->handleFail();
break;
}
}
请注意$echo = @$worker->echo(1);
行和下面的检查。如果服务器不可用,则echo()
输出PHP警告并返回false
。
GearmanException
在我们的设置中从未抛出。
对于基本解决方案,您可以使用如下代码:
try {
while ($worker->work() || GEARMAN_TIMEOUT == $worker->returnCode()) {
if (GEARMAN_TIMEOUT == $worker->returnCode()) {
echo "Timeout...n";
} elseif (GEARMAN_SUCCESS != $worker->returnCode()) {
echo "Fail...n";
break;
}
}
} catch (GearmanException $e) {
echo "Exception caused!n";
}
但是你不能让worker活着,因为它需要连接。我建议使用superord来自动重启工人。