多名 Gearman 工人获得相同的工作

Multiple Gearman workers receive same job

我同时有两个工人运行,目前他们都在同一时间接受同一份工作。我的印象是,虽然工人 A 是 运行 一份工作,但工人 B 会收到队列中的下一份工作。每个作业大约需要 10 秒才能完成。我该如何实现?

我已将我的代码简化为:(假设客户端在两秒内被调用两次)

客户

$client = new GearmanClient();
$client->addServer();

$client->doBackground("my_task");

工人

$worker = new GearmanWorker();
$worker->addServer();
$worker->addFunction("my_task", "my_task_fn");

while($worker->work());

function my_task_fn($job) {
    echo $job->handle(); // both workers show same job #, I want each worker getting a different job
    sleep(10);
}

您所描述的情况不应该发生,我提供了一个示例供您了解。在工作人员响应响应之前,客户端脚本不会完成。但是您可以通过将 'doNormal' 更改为 'doBackground' 来轻松适应。在您的 worker 函数中放置一个睡眠计数器以减慢 worker 的速度,并将您的客户端置于一个循环中以创建大量作业以查看该过程的工作更轻松。

客户端代码

// Create our client object
$client = new GearmanClient();

// Add a server
$client->addServer(); // by default host/port will be "localhost" & 4730

echo "Sending job\n";

// Send reverse job
$result = $client->doNormal("reverse", "Hello!");
if ($result) {
    echo "Success: $result\n";
}

工人代码

// Create our worker object
$worker = new GearmanWorker();

// Add a server (again, same defaults apply as a worker)
$worker->addServer();

// Inform the server that this worker can process "reverse" function calls
$worker->addFunction("reverse", "reverse_fn");

while (1) {
    print "Waiting for job...\n";
    $ret = $worker->work(); // work() will block execution until a job is delivered
    if ($worker->returnCode() != GEARMAN_SUCCESS) {
        break;
    }
}

// A much simple reverse function
function reverse_fn(GearmanJob $job) {
    $workload = $job->workload();
    echo "Received job: " . $job->handle() . "\n";
    echo "Workload: $workload\n";
    $result = strrev($workload);
    echo "Result: $result\n";
    return $result;
}