结合 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 "Starting\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 "Connected to {$gmw->server['host']}:{$gmw->server['port']}...\n";
print "Waiting for jobs...\n";
while ($gmw->work()) {
if ($gmw->returnCode() != GEARMAN_SUCCESS) {
echo "return_code: " . $gmw->returnCode() . "\n";
break;
}
}
echo "DONE\n";
} else {
echo "Unable to connect to any gearman-job-servers.".PHP_EOL;
};
function reverseString_fn($job)
{
echo "Received job: " . $job->handle() . "\n";
$workload = $job->workload();
$workload_size = $job->workloadSize();
echo "Workload: $workload ($workload_size)\n";
for ($x= 0; $x < $workload_size; $x++) {
echo "Sending status: " . ($x + 1) . "/$workload_size complete\n";
$job->sendStatus($x+1, $workload_size);
$job->sendData(substr($workload, $x, 1));
sleep(1);
}
$result= strrev($workload);
echo "Result: $result\n";
return $result;
}