网站首页php

PHP多进程采集cli模式及web模式分析

发布时间:2016-06-13 01:44:23编辑:阅读(4596)

    一、在cli模式下开启多进程。

        在cli下php开启多进程,需要开启pcntl扩展(限linux).

        a、在编译PHP时在./configrue后加上--enable-pcntl

        b、若已安装过PHP,可以直接编译pcntl源文件

    # cd /usr/local/src/php-5.6.1/ext/pcntl
    # phpize
    # ./configure --with-php-config=/usr/local/php/bin/php-config
    # make && make install
    
    把pcntl.so  加到php.ini中
    extension=pcntl.so
    重新启动php-fpm或apache完成。


    然后就可以疯狂的开多进程了, 从网上找了个简化操作的库,在cli下会自动统计采集数据量,挺好用.

    process.lib.php

    curl.lib.php

    采集代码看起来非常简略(run.php):

    <?php
    include('./process.lib.php');
    include('./curl.lib.php');
        
    multi_process($argv[1], true);
        
    while(true){
            $tid    =    mp_counter('tid'); //$tid用于安装计数器种子,每次执行时+1
            $url    =    "http://bbs.xxxxx.com/forum-1889-{$tid}.html";
            do{
                $html=    curl_get($url, 'utf-8');
            }while($html===FALSE);
            
            //对html内容进行处理
    }

    在cli下执行:

    php -f run.php 1000

    这样就可以开启1000个进程开始采集了。(注意你的服务器资源,可以根据cpu数量和内存容量多调试,找到最优的开启进程数。)



    二、在web模式下开启多进程。

        在web模式下开多进程的话, 我用的是鸟哥的rpc框架yar。

        安装如下:

    #wget 
    #tar -zxvf yar-2.0.0.tgz
    #cd yar-2.0.0
    #/usr/local/php/v70/bin/phpize
    #./configure --with-php-config=/usr/local/php/v70/bin/php-config
    #make && make install 
    
    在PHP.ini中添加yar.so
    extension=yar.so
    重新启动php-fpm或apache完成。

    使用的话,要先编写服务端(rpc.php):


    <?php
    include('./curl.lib.php');
    class RPC{
        public function getData($tid){        
            $url   =  "http://bbs.xxxxx.com/forum-1889-{$tid}.html";
            $html    =  curl_get($url, 'utf-8');
            //对html内容进行处理
        }
    }
    $service = new Yar_Server(new RPC());
    $service->handle();


    然后,就可以去客户端跑起多开了, 嗯 ,貌似是模拟的多进程,开了1000个并发。

    数据处理主要在服务端完成,挺大的局限性,不过也能很好的完成任务:)

    <?php
        function callback($retval, $callinfo) {
            if ($callinfo == NULL) {
               echo 'Done';
               return TRUE;
            }     
            print_r($retval);
        }
        
      for($i=1;$i<1000;$i++){        
           Yar_Concurrent_Client::call("http://host/rpc.php", "getData", array($i), "callback");    
      }    
      Yar_Concurrent_Client::loop();



评论