结合brainreflex和iloveapplepie的建议,以及数小时的测试。这避免了跨平台Gearman不同版本之间的一些错误。
它逐步遍历服务器列表,如果所有服务器都不可访问,则会失败。
我还对客户端使用与“class SmartGearmanClient extends GearmanClient”相同的重写。
<?php class SmartGearmanWorker extends GearmanWorker
{
public $server = false;
public function connect($servers = array( array('host' => '127.0.0.1', 'port' => '4730') ))
{
$connected = false;
foreach ($servers as $server) {
$c = new GearmanClient();
$c->addServer($server['host'], $server['port'], false);
if (@$c->ping('ping')) {
$this->addServer($server['host'], $server['port']);
$connected=true;
$this->server = array(
'host'=>$server['host'],
'port'=>$server['port']
);
break; }
}
return $connected;
}
}
echo "启动中...\n";
$servers = array(
array('host' => '127.0.0.1', 'port' => '4730'),
array('host' => '127.0.0.1', 'port' => '4731'),
array('host' => '127.0.0.1', 'port' => '4732'),
array('host' => '127.0.0.2', 'port' => '4730'),
array('host' => '192.168.204.10', 'port' => '4730')
);
$gmw= new SmartGearmanWorker();
if ($gmw->connect($servers)) {
$gmw->addFunction("reverseString", "reverseString_fn");
print "已连接到 {$gmw->server['host']}:{$gmw->server['port']}...\n";
print "等待任务...\n";
while ($gmw->work()) {
if ($gmw->returnCode() != GEARMAN_SUCCESS) {
echo "返回码: " . $gmw->returnCode() . "\n";
break;
}
}
echo "完成\n";
} else {
echo "无法连接到任何gearman-job-servers.".PHP_EOL;
};
function reverseString_fn($job)
{
echo "收到任务: " . $job->handle() . "\n";
$workload = $job->workload();
$workload_size = $job->workloadSize();
echo "工作负载: $workload ($workload_size)\n";
for ($x= 0; $x < $workload_size; $x++) {
echo "发送状态: " . ($x + 1) . "/$workload_size 完成\n";
$job->sendStatus($x+1, $workload_size);
$job->sendData(substr($workload, $x, 1));
sleep(1);
}
$result= strrev($workload);
echo "结果: $result\n";
return $result;
}