我正在通过gearman运行分布式作业。我试图转换1000个大小为10 MB的pdf文件。我能够设置它并获得编码的pdf文件。
我有以下代码:
gearman_client.php(仅用于初始化)
<?php
class gearman_client{
static $timeout = 5000;
private static function addServerToCLient($client, $server){
$added = 0;
$client->setTimeout(self::$timeout);
$server = explode(':', $server);
$job_server = $server[0];
if(array_key_exists(1, $server))
$job_server_port = $server[1];
else
$job_server_port = 4730; //default port
try{
$added = $client->addServer($job_server, $job_server_port);
}
catch(GearmanException $e){
error_log(sprintf("GearmanException: %s .Error adding Gearman Server: %s, port: %s",$e->getMessage(), $job_server, $job_server_port), false);
}
return $added;
}
public static function initialize(){
$client = null;
$servers = explode(',', GEARMAN_JOB_SERVERS);
$added = 0;
//To accomodate Gearman bug
$flag = 0;
foreach($servers as $server){
if(!$flag){
unset($client);
$client = new GearmanClient();
}
$added = self::addServerToCLient($client, $server);
if($added)
$flag = 1;
}
if($flag)
return $client;
return 0;
}
}
Gearman客户
$gmclient = gearman_client::initialize();
if(!$gmclient){
$this->error("Gearman server error","Could not create a gearman client object with a running Gearman Server");
return;
}
$pdfdata = array(
"id_host" => $this->id_host,
"id_vhost" => $this->id_vhost,
"id_contents" => $id_contents
);
$job_handle = $gmclient->doBackground("pdf_convert", json_encode($pdfdata));
if ($gmclient->returnCode() != GEARMAN_SUCCESS){
error_log("Gearman client: Bad Return code. Error while submitting background job");
}
Gearman工作人员
$worker = new GearmanWorker();
$worker->addServer("192.0.1.118");
$worker->addFunction("pdf_convert", function(GearmanJob $job) {
$workload = json_decode($job->workload());
$id_host = $workload->id_host;
$id_vhost = $workload->id_vhost;
$id_contents = $workload->id_contents;
contents_path($id_host, $id_vhost, $id_contents);
pdf($id_host, $id_vhost, $id_contents);
// You would then, of course, actually call this:
//mail($workload->email, $workload->subject, $workload->body);
});
while ($worker->work());
一切似乎都运作良好。但是,我看到即使我启动了多个gearman worker实例,也只有一个工作总是很忙(我可以通过telnet接口看到)。
如果我在工人代码中引入sleep(30)
,那么我开始看到其他工人从事工作。
这是正常行为吗?