Example #1 Basic Gearman client and worker
This example shows a very simple client and worker. The client sends a string to the job server, and the worker reverses the string and sends it back. The job is performed synchronously.
<?php
# Create our client object.
$gmclient= new GearmanClient();
# Add default server (localhost).
$gmclient->addServer();
echo "Sending job\n";
# Send reverse job
do
{
$result = $gmclient->do("reverse", "Hello!");
# Check for various return packets and errors.
switch($gmclient->returnCode())
{
case GEARMAN_WORK_DATA:
echo "Data: $result\n";
break;
case GEARMAN_WORK_STATUS:
list($numerator, $denominator)= $gmclient->doStatus();
echo "Status: $numerator/$denominator complete\n";
break;
case GEARMAN_WORK_FAIL:
echo "Failed\n";
exit;
case GEARMAN_SUCCESS:
break;
default:
echo "RET: " . $gmclient->returnCode() . "\n";
exit;
}
}
while($gmclient->returnCode() != GEARMAN_SUCCESS);
?>
<?php
echo "Starting\n";
# Create our worker object.
$gmworker= new GearmanWorker();
# Add default server (localhost).
$gmworker->addServer();
# Register function "reverse" with the server. Change the worker function to
# "reverse_fn_fast" for a faster worker with no output.
$gmworker->addFunction("reverse", "reverse_fn");
print "Waiting for job...\n";
while($gmworker->work())
{
if ($gmworker->returnCode() != GEARMAN_SUCCESS)
{
echo "return_code: " . $gmworker->returnCode() . "\n";
break;
}
}
function reverse_fn($job)
{
echo "Received job: " . $job->handle() . "\n";
$workload = $job->workload();
$workload_size = $job->workloadSize();
echo "Workload: $workload ($workload_size)\n";
# This status loop is not needed, just showing how it works
for ($x= 0; $x < $workload_size; $x++)
{
echo "Sending status: " . ($x + 1) . "/$workload_size complete\n";
$job->sendStatus($x, $workload_size);
sleep(1);
}
$result= strrev($workload);
echo "Result: $result\n";
# Return what we want to send back to the client.
return $result;
}
# A much simpler and less verbose version of the above function would be:
function reverse_fn_fast($job)
{
return strrev($job->workload());
}
?>
以上例程的输出类似于:
% php reverse_worker.php Starting Waiting for job... Received job: H:foo.local:36 Workload: Hello! (6) Sending status: 1/6 complete Sending status: 2/6 complete Sending status: 3/6 complete Sending status: 4/6 complete Sending status: 5/6 complete Sending status: 6/6 complete Result: !olleH
% php reverse_client.php Starting Sending job Status: 1/6 complete Status: 2/6 complete Status: 3/6 complete Status: 4/6 complete Status: 5/6 complete Status: 6/6 complete Success: !olleH
rjha at 3mik dot com (2012-07-09 08:16:28)
The client should print the result received from job server.
<?php
// switch(...) {
case GEARMAN_SUCCESS:
echo "result : $result \\n" ;
break;
// }
?>