Home > Backend Development > PHP Tutorial > PHP uses swoole to implement multi-threaded crawler

PHP uses swoole to implement multi-threaded crawler

藏色散人
Release: 2023-04-08 08:34:01
forward
3308 people have browsed it

In swoole, php can use its method of starting sub-processes to realize multiple processes of php:

<?php
$s_time = time();
echo &#39;开始时间:&#39;.date(&#39;H:i:s&#39;,$s_time).PHP_EOL;
//进程数
$work_number=6;
 
//
$worker=[];
 
//模拟地址
$curl=[
    &#39;https://blog.csdn.net/feiwutudou&#39;,
    &#39;https://wiki.swoole.com/wiki/page/215.html&#39;,
    &#39;http://fanyi.baidu.com/?aldtype=16047#en/zh/manager&#39;,
    &#39;http://wanguo.net/Salecar/index.html&#39;,
    &#39;http://o.ngking.com/themes/mskin/login/login.jsp&#39;,
    &#39;https://blog.csdn.net/marksinoberg/article/details/77816991&#39;
];
 
//单线程模式
// 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 &#39;结束时间:&#39;.date(&#39;H:i:s&#39;,$e_time).PHP_EOL;
 
echo &#39;所用时间:&#39;.($e_time-$s_time).&#39;秒&#39;.PHP_EOL;
?>
Copy after login

Multi-thread execution results:

PHP uses swoole to implement multi-threaded crawler

For comparison, the single-thread result:

PHP uses swoole to implement multi-threaded crawler

# The improvement is very obvious!

For more PHP related knowledge, please visit PHP Tutorial!

The above is the detailed content of PHP uses swoole to implement multi-threaded crawler. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template