gearman的YUM安装及PHP应用
默认的yum是没有gearmand的,需要添加源。
- rpm -ivh http://dl.iuscommunity.org/pub/ius/stable/Redhat/6/x86_64/epel-release-6-5.noarch.rpm
源添加完后
- yum install gearmand libgearman-devel
- wget http://pecl.php.net/get/gearman
获取php-gearman扩展
然后解压后./phpize
./configure
./make && make install
然后重启一下服务器就OK了。
测试client&worker(同步模式)
client.php
- <?php
- $client= new GearmanClient();
- $client->addServer();
- echo $client->do("reverse", "Hello World!");
- ?>
worker.php
- <?php
- $worker= new GearmanWorker();
- $worker->addServer();
- $worker->addFunction("reverse", "my_reverse_function");
- while ($worker->work());
- function my_reverse_function($job)
- {
- for($i = 0; $i < 10; $i++){
- sleep(1);
- echo "{$i}\n";
- }
- return strrev($job->workload());
- }
- ?>
可以看到如果多个client.php同时执行的话,只有一个worker在工作,其他的都会阻塞在那里等待结果。
然后我们测试异步模式
client-async.php
- <?php
- $client= new GearmanClient();
- $client->addServer();
- echo $client->doBackground("reverse", "Hello World!");
- ?>
worker.php不变。
每次执行client-async.php后立即返回,然后worker.php默默地在那执行。client-async.php执行多次后,只有一个worker在工作,gearman会在worker执行完当前任务后派发给它前面累积的任务,任务不会丢失(暂没有测试最大能够积累多少个任务)。