PHP 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();
} 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
如何在客户端无法连接到服务器时捕获错误?
答案 0 :(得分:2)
我们已添加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
永远不会被我们的设置抛出。
答案 1 :(得分:1)
对于基本解决方案,您可以使用以下代码:
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";
}
但你不能让工人活着,因为它需要连接。我建议使用Supervisord自动重启工作人员。