Server
require 'Doctrine/Common/ClassLoader.php';
use Doctrine\Common\ClassLoader;
use Doctrine\DBAL\DriverManager;
use Doctrine\DBAL\Configuration;
$classLoader = new ClassLoader('Doctrine', '/www/DoctrineDBAL-2.3.4/');
$classLoader->register();
$config = new Configuration();
$connectionParams = array(
'dbname' => 'example',
'user' => 'www',
'password' => 'password',
'host' => '192.168.2.1',
'driver' => 'pdo_mysql',
);
$conn = DriverManager::getConnection($connectionParams, $config);
$host = '127.0.0.1';
$port = 4730;
echo "Starting\n";
# Create our worker object.
$gmworker= new GearmanWorker();
# Add default server (localhost).
$gmworker->addServer($host, $port);
# Register function "reverse" with the server. Change the worker function to
# "reverse_fn_fast" for a faster worker with no output.
$gmworker->addFunction("members", "members");
print "Waiting for job...\n";
while($gmworker->work())
{
if ($gmworker->returnCode() != GEARMAN_SUCCESS)
{
echo "return_code: " . $gmworker->returnCode() . "\n";
break;
}
}
function members($job)
{
global $conn;
$param = unserialize($job->workload());
print_r($param);
$sql = "SELECT username FROM members limit ".$param['limit'].",".$param['offset'];
$stmt = $conn->query($sql);
while ($row = $stmt->fetch()) {
//printf("%s\r\n", );
$result[] = $row['username'];
}
return serialize($result);
}
Client
# create our client object
$gmclient= new GearmanClient();
# add the default server (localhost)
$gmclient->addServer();
# run reverse client in the background
$job_handle = $gmclient->doNormal("members",serialize(array('limit'=>5,'offset'=>10)));
if ($gmclient->returnCode() == GEARMAN_SUCCESS)
{
print_r(unserialize($job_handle));
}
运行结果
$ php client.php
Array
(
[0] => 257000005
[1] => 257000006
[2] => 257000009
[3] => 257000010
[4] => 257000011
[5] => 257000012
[6] => 257000013
[7] => 257000014
[8] => 257000015
[9] => 257000016
)