温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

PHP怎样使用swoole实现多线程爬虫?

发布时间:2020-05-21 22:54:16 来源:亿速云 阅读:259 作者:鸽子 栏目:编程语言

在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.baidu.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;
?>

多线程执行结果:

PHP怎样使用swoole实现多线程爬虫?

作为对比,单线程结果:

PHP怎样使用swoole实现多线程爬虫?

提升十分明显!

以上就是PHP使用swoole实现多线程爬虫的详细内容,更多请关注亿速云其它相关文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI