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

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

多线程执行结果:

e9be6496b823ae76b84a323486e37f7e.png

作为对比,单线程结果:

4e0bbb8adae2882e81570f7139c7fe72.png

提升十分明显!

更多PHP相关知识,请访问PHP教程!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值