基本用法

示例 #1 基本 Gearman 客户端和工作程序

此示例展示了一个非常简单的客户端和工作程序。客户端将字符串发送到作业服务器,工作程序反转字符串并将其发送回。作业同步执行。

<?php

# 创建我们的客户端对象。
$gmclient= new GearmanClient();

# 添加默认服务器(localhost)。
$gmclient->addServer();

echo
"Sending job\n";

# 发送反转作业
do
{
$result = $gmclient->doNormal("reverse", "Hello!");

# 检查各种返回数据包和错误。
switch($gmclient->returnCode())
{
case
GEARMAN_WORK_DATA:
echo
"Data: $result\n";
break;
case
GEARMAN_WORK_STATUS:
list(
$numerator, $denominator)= $gmclient->doStatus();
echo
"Status: $numerator/$denominator complete\n";
break;
case
GEARMAN_WORK_FAIL:
echo
"Failed\n";
exit;
case
GEARMAN_SUCCESS:
echo
"Success: $result\n";
break;
default:
echo
"RET: " . $gmclient->returnCode() . "\n";
exit;
}
}
while(
$gmclient->returnCode() != GEARMAN_SUCCESS);

?>
<?php

echo "Starting\n";

# 创建我们的工作程序对象。
$gmworker= new GearmanWorker();

# 添加默认服务器(localhost)。
$gmworker->addServer();

# 在服务器上注册函数 "reverse"。将工作程序函数更改为
# "reverse_fn_fast" 以获得更快的无输出工作程序。
$gmworker->addFunction("reverse", "reverse_fn");

print
"Waiting for job...\n";
while(
$gmworker->work())
{
if (
$gmworker->returnCode() != GEARMAN_SUCCESS)
{
echo
"return_code: " . $gmworker->returnCode() . "\n";
break;
}
}

function
reverse_fn($job)
{
echo
"Received job: " . $job->handle() . "\n";

$workload = $job->workload();
$workload_size = $job->workloadSize();

echo
"Workload: $workload ($workload_size)\n";

# 此状态循环不需要,只是展示其工作原理
for ($x= 0; $x < $workload_size; $x++)
{
echo
"Sending status: " . ($x + 1) . "/$workload_size complete\n";
$job->sendStatus($x, $workload_size);
sleep(1);
}

$result= strrev($workload);
echo
"Result: $result\n";

# 返回我们要发送回客户端的内容。
return $result;
}

# 上述函数的更简单、更简洁的版本是:
function reverse_fn_fast($job)
{
return
strrev($job->workload());
}

?>

上面的示例将输出类似于以下内容

% php reverse_worker.php
Starting
Waiting for job...
Received job: H:foo.local:36
Workload: Hello! (6)
Sending status: 1/6 complete
Sending status: 2/6 complete
Sending status: 3/6 complete
Sending status: 4/6 complete
Sending status: 5/6 complete
Sending status: 6/6 complete
Result: !olleH
% php reverse_client.php
Starting
Sending job
Status: 1/6 complete
Status: 2/6 complete
Status: 3/6 complete
Status: 4/6 complete
Status: 5/6 complete
Status: 6/6 complete
Success: !olleH

添加说明

用户贡献的说明 1 条说明

dmitriy dot baibuhtin at ya dot ru
7 年前
客户端示例无效。由于 doNormal 方法是同步的,因此进度不会显示在客户端侧。
代码只会在 doNormal 完成后执行。
<?php
case GEARMAN_WORK_STATUS:
list(
$numerator, $denominator)= $gmclient->doStatus();
echo
"Status: $numerator/$denominator complete\n";
break;
?>
To Top