Combining recommendations from brainreflex and iloveapplepie, as well as hours of testing. This avoids some bugs in cross versions of gearman across platforms.
It steps though the server list and fails if all are inaccessible.
I also use the same override as "class SmartGearmanClient extends GearmanClient" for the clients.
<?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;
}