PHP使用Gearman
下面的简单例子仅为说明PHP如何使用Gearman,不具备实际生产意义.
一个简单的worker:[root@centos192 worker]# cat myworker.php
$worker = new GearmanWorker();
$worker->addServer('192.168.1.192', 4730);
$worker->addFunction('sayhello', function(GearmanJob $job){
$name = $job->workload();
return "hello, " . $name;
});
$worker->addFunction('logMsg', function(GearmanJob $job){
$msg = $job->workload();
file_put_contents(__DIR__ . '/Msg.log', $msg, FILE_APPEND);
});
while ($worker->work()){
usleep(50000);
}
以守护进程方式启动worker:# nohup php myworker.php >/dev/null 2>&1 &
一个发送任务处理请求的client:[root@centos191 client]# cat myclient.php
$name = $argv[1];
if (empty($name)) {
echo "Usage: $argv[0] {name}";
exit(1);
}
try {
$client = new GearmanClient();
$client->addServer('192.168.1.192', 4730);
} catch(Exception $e){
echo "oops", $e->getMessage();
exit(1);
}
// 同步处理(Blocking),返回直接的处理结果
$result = $client->doNormal('sayhello', $name);
echo $result . PHP_EOL;
// 异步处理(Non-Blocking),仅返回一个处理状态的句柄
$job_handle = $client->doBackground('logMsg', $name);
echo $job_handle . PHP_EOL;
运行myclient.php:[root@centos191 client]# php myclient.php "Jose"
hello, Jose
H:centos192:5
一个发出并行处理任务请求的例子tasksclient:[root@centos191 client]# cat tasksclient.php
try {
$client = new GearmanClient();
$client->addServer('192.168.1.192', 4730);
} catch(Exception $e){
echo "oops", $e->getMessage();
exit(1);
}
$client->setCompleteCallback(function(GearmanTask $task){
echo 'Completed task:: id :', $task->unique(), ' , handled result:', $task->data(), PHP_EOL;
});
$client->addTask('sayhello', 'Jose', null, 1);
$client->addTask('sayhello', 'John', null, 2);
$client->addTaskBackground('logMsg', 'Peter');
$client->runTasks();
运行tasksclient:[root@centos191 client]# php tasksclient.php
Completed task:: id :2 , handled result:hello, John
Completed task:: id :1 , handled result:hello, Jose