PHP使用swoole实现多线程爬虫-php教程

资源魔 36 0
正在swoole中,php能够借助其启动子过程的形式,完成php的多过程:

<?php
$s_time = time();
echo '开端工夫:'.date('H:i:s',$s_time).PHP_EOL;
//过程数
$work_number=6;
 
//
$worker=[];
 
//模仿地点
$curl=[
    'https://blog.csdn.net/feiwutudou',
    'https://wiki.swoole.com/wiki/page/215.html',
    'http://fanyi.百度.com/?aldtype=16047#en/zh/manager',
    'http://wanguo.net/Salecar/index.html',
    'http://o.ngking.com/themes/mskin/login/login.jsp',
    'https://blog.csdn.net/marksinoberg/article/details/77816991'
];
 
//复线程模式
// foreach ($curl as $v) {
// echo curldeta($v);
// }
 
//创立过程
for ($i=0; $i < $work_number; $i++) {
    //创立多线程
    $pro=new swoole_process(function(swoole_process $work) use($i,$curl){
        //猎取html文件
        $content=curldeta($curl[$i]);
        //写入管道
        $work->write($content.PHP_EOL);
    },true);
    $pro_id=$pro->start();
    $worker[$pro_id]=$pro;
}
//读取管道内容
foreach ($worker as $v) {
    echo $v->read().PHP_EOL;
}
 
//模仿爬虫
function curldeta($curl_arr)
{//file_get_contents
    echo $curl_arr.PHP_EOL;
    file_get_contents($curl_arr);
}
 
//过程收受接管
swoole_process::wait();
 
$e_time = time();
echo '完结工夫:'.date('H:i:s',$e_time).PHP_EOL;
 
echo '所历时间:'.($e_time-$s_time).'秒'.PHP_EOL;
?>

多线程执行后果:

4d8084991537fd94f8576f37ac80f21.png

作为比照,复线程后果:

a3d1d04d9063f5c55fc958a0e72162b.png

晋升非常显著!

更多PHP相干常识,请拜访PHP教程!

以上就是PHP应用swoole完成多线程爬虫的具体内容,更多请存眷资源魔其它相干文章!

标签: php php开发教程 php开发资料 php开发自学

抱歉,评论功能暂时关闭!