首页 > 编程 > PHP > 正文

PHP使用swoole实现多线程爬虫

2020-03-22 16:18:34
字体:
来源:转载
供稿:网友
在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',    'https://fanyi.baidu.com/?aldtype=16047#en/zh/manager',    'https://wanguo.net/Salecar/index.html',    'https://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实现多线程爬虫的详细内容,更多请关注电脑知识其它相关文章!

郑重声明:本文版权归原作者所有,转载文章仅为传播更多信息之目的,如作者信息标记有误,请第一时间联系我们修改或删除,多谢。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表