Gearman并行处理,中间给出输出


Gearman processing in parallel and give output intermedeate

我使用Gearman和Slim PHP创建restful API,其中:

用户将调用restful API并发送一个文件url。这将:

  1. 下载文件-并向用户发送唯一的文件id作为http响应
  2. 发送响应时,我想开始处理文件
  3. 用户可以通过GET www.example.com/api/status API调用来检查进程的状态

对于文件下载部分,我已经使用gearman to donnormal,但是状态响应也只有在处理完成后才发送。另外,如何获取每个客户端进程的状态?我需要更多的帮助,如何准确地我可以构建相同的和排队处理的一些细节,因为我是新的gearman。

您需要使用jobstatus和doBackground()。首先,您需要初始化传输。这是通过将任务发送到后台并向用户发送一个作业句柄来完成的。您可以通过yourserver.com/api/file-transfer调用它,并且必须发送带有文件集的POST请求。答案是json对象。

<?php
// use composer for slim
require_once "vendor/autoload.php"; 
$app = new 'Slim'Slim();
// init file transfer
$app->post('/file-transfer', function () use ($app) {
    $resp = array();
    try {
        // get file url
        $fileurl = $app->request->post('fileurl');
        $data = json_encode(array("fileurl"=>$fileurl);
        // send to gearman
        $client = new GearmanClient();
        $client->addServer();
        // store the gearman handle and send the task to the background
        $jobHandle = $client->doBackground("fileUpload", $data);
        if ($client->returnCode() != GEARMAN_SUCCESS) throw new Exception("Could not add the job to the queue.", 1);
        $resp["msg"] = "File upload queued";
        $resp["handle"] = $jobHandle;
    } catch(Exception $e) {
        // some error handling
        $resp["msg"] = "There occured a strange error.";
        $resp["error"] = true;
    } finally {
        $response = $app->response();
        $response['Content-Type'] = 'application/json';
        $response->status(200);
        $response->body(json_encode($resp));    
    }
});
?>

在第二步中,用户需要使用作业句柄(他从第一个调用中收到的)查询服务器:

$app->post('/file-status', function () use ($app) {
    $jobHandle = $app->request->params('handle');
    $resp = array();
    try {
        // ask for job status
        $client = new GearmanClient();
        $client->addServer();
        $stat = $client->jobStatus($jobHandle);
        if (!$stat[0]) { // it is done
            $resp["msg"]    = "Transfer completed.";
        } else {
            $resp["msg"]    = "Transfer in progress.";
            $w = (float)$stat[2]; // calculate the percentage
            $g = (float)$stat[3];
            $p = ($g>0)?$w/g*100:0;
            $resp["percentage"] = $p;
        }
    } catch(Exception $e) {
            // some error handling
            $resp["msg"] = "There occured a strange error.";
            $resp["error"] = true;
    } finally {
        $response = $app->response();
        $response['Content-Type'] = 'application/json';
        $response->status(200);
        $response->body(json_encode($resp));    
    }
});

在第二个请求中,您有来自$client->jobStatus()的$stats数组。$stats[0]告诉您作业是否为gearman服务器所知。第二个元素检查是否正在运行,3和4(2/3)用于计算传输的百分比(您需要自己设置这些值!)。