gearman php 分布式搭建

上一篇博客已经成功搭建了gearman环境:

centos安装gearmand及php扩展

下面我们来实现分布式,也就是万一一个进程死掉或者一台服务器当掉的情况

假设两台服务器:192.168.10.102 和 192.168.10.103

102的work代码如下:

<?php
  $worker= new GearmanWorker();
  $worker->addServer();
  $worker->addServer('192.168.10.103',4730);
        $worker->addFunction("title", "title_function");
  while ($worker->work());

  function title_function($job)
  {
    return ucwords(strtolower($job->workload())) . "102";
  }
?>

103的work代码与102基本相同

<?php
  $worker= new GearmanWorker();
  $worker->addServer();
  $worker->addServer('192.168.10.102',4730);
        $worker->addFunction("title", "title_function");
  while ($worker->work());

  function title_function($job)
  {
    return ucwords(strtolower($job->workload())) . "new103";
  }
?>

分别启动work进程:/usr/local/php/bin/php test/localhost/worker.php &

103的client.php 代码如下:

<?php
$client= new GearmanClient();
$client->addServer('127.0.0.1',4730);
$client->addServer('192.168.10.102',4730);
print $client->do("title", "AlL THE World's a sTagE");
print "\n";
?>

执行 /usr/local/php/bin/php client.php 输出为:All The World's A Stage102,说明他在102执行了请求。

测试一:如果挂掉一个进程,效果如何?

1、修改102的work程序

<?php
  $worker= new GearmanWorker();
  $worker->addServer('127.0.0.1',4730);
        $worker->addFunction("title", "title_function");
  while ($worker->work());

  function title_function($job)
  {
    return ucwords(strtolower($job->workload())) . "new102";
  }
?>

2、启动另外一个work进程 /usr/local/php/bin/php work.php & 。注意此时102有两个进程。

3、再次执行 /usr/local/php/bin/php client.php 输出为:All The World's A Stagenew102,说明第二个work进程接受了请求。

4、kill第二个进程(假设挂掉一个进程)。再次执行 /usr/local/php/bin/php client.php 输出为:All The World's A Stagen102。

5、kill第一个进程(假设挂掉102这台服务器)。

6、执行 /usr/local/php/bin/php client.php 输出为:All The World's A Stagen103

摘自:http://blog.s135.com/dips/

原文地址:https://www.cnblogs.com/liqiu/p/2737090.html