10/14/13

gearman 多服务器负载均衡应用

1、启动gearman 进程

分别在192.168.0.197和192.168.0.198服务器上启动:

/opt/phpdba/gearman/sbin/gearmand -u root -d

2、执行服务器端php处理脚本

分别在192.168.0.197和192.168.0.198服务器上启动:

Worker.php:

<?php
include(“/opt/phpdba/www/html/xxxx/kernel.php”);
Using(‘classes.apply’);
Using(‘classes.key_word’);
$worker= new GearmanWorker();

$worker->addServer("192.168.0.197");

$worker->addServer("192.168.0.198");

$worker->addFunction(“addRecordLog”, “addRecordLog_function”);
while ($worker->work()){
if($worker->returnCode() != GEARMAN_SUCCESS){
echo “return_code: “.$worker->returnCode().”\n”;
break;
}
}

function addRecordLog_function($job){
$status = $job->workload();
$condition = “status=’{$status}’”;
$applylist = Apply::getApply($condition,0,10);
if($applylist){
foreach($applylist as $applyinfo){
$result = key_word::getApplyKeyword($applyinfo['id'],strip_tags($applyinfo['content']));
}
return “run ok”;
}else{
return “list is empty!”;
}
}
?>

3、客户端php执行脚本

Client.php:

<?php
include(“/opt/phpdba/www/html/xxxx/kernel.php”);
$client= new GearmanClient();

$client->addServer("192.168.0.197");

$client->addServer("192.168.0.198");

#多服务器负载均衡处理

do
{
$result = $client->do(“addRecordLog”,”normal”);

switch($client->returnCode())
{
case GEARMAN_WORK_DATA:
echo “Data:$result\n”;
break;
case GEARMAN_WORK_STATUS:
list($numerator,$denominator) = $client->doStatus();
echo “Status:$numerator/$denominator complete\n”;
break;
case GEARMAN_WORK_FAIL:
echo “Failed\n”;
exit;
case GEARMAN_SUCCESS:
break;
default:
echo “RET: “.$client->returnCode().”\n”;
echo “Error: “.$client->error().”\n”;
echo “Errno: “.$client->getErrno().”\n”;
exit;
}
}
while($client->returnCode() != GEARMAN_SUCCESS);

echo “Success: $result\n”;

?>