首頁  >  文章  >  php框架  >  講解thinkphp5.1如何實作多執行緒爬蟲

講解thinkphp5.1如何實作多執行緒爬蟲

藏色散人
藏色散人轉載
2021-11-03 16:06:283592瀏覽

下面thinkphp框架教學欄位將跟大家講解thinkphp5.1 利用cli命令列 Guzzle類別庫實作多執行緒爬蟲,希望對需要的朋友有幫助!

建立一個cli指令

php think make:command Thread thread

測試能否成功執行

php think thread

安裝Guzzle類別庫

文件位址:guzzle文件位址(https://guzzle-cn.readthedocs.io/zh_CN/latest/quickstart.html)

實現程式碼

<?php
/**
 * Created by.
 * User: Jim
 * Date: 2020/9/29
 * Time: 14:31
 */

namespace app\command;

use GuzzleHttp\Client;
use GuzzleHttp\Pool;
use think\console\Command;
use think\console\Input;
use think\console\Output;

/**
 * Guzzle
 * Class Thread
 * @package app\command
 * 文档地址 https://guzzle-cn.readthedocs.io/zh_CN/latest/quickstart.html
 */

class Thread extends Command
{

    /**
     * 请求的总次数
     * @var int
     */
    protected $totalPageCount = 50;
    /**
     * 当前请求的次数
     * @var int
     */
    protected static $counter = 1;
    /**
     * 线程的数量
     * @var int
     */
    protected $threads = 20;

    protected function configure()
    {
        // 指令配置
        $this->setName(&#39;thread&#39;);
        // 设置参数

    }

    protected function execute(Input $input, Output $output)
    {

        $client = new Client();
        $requests = function ($total) use ($client) {
            foreach (range(1, $total) as $r) {
                $uri = &#39;https://apinew.juejin.im/content_api/v1/short_msg/detail&#39;;
                yield function () use ($client, $uri) {
                    return $client->postAsync($uri, [
                        &#39;verify&#39; => false,
                        &#39;json&#39; => [
                            &#39;msg_id&#39; => &#39;6845185452727599118&#39;
                        ]
                    ]);
                };
            }

        };

        $pool = new Pool($client, $requests($this->totalPageCount), [
            &#39;concurrency&#39; => $this->threads,
            // 请求成功
            &#39;fulfilled&#39; => function ($response, $index) use ($output) {
                $res = $response->getBody()->getContents();
                $output->writeln($res);
                $output->writeln("正在执行第{$index}个·····");
                if ($this->checkThreadIsEnd() == true) {
                    $output->writeln("------------请求结束---------");
                    return false;
                }
            },
            // 请求失败
            &#39;rejected&#39; => function ($reason, $index) use ($output) {
                $output->writeln("执行失败,{$reason}");
            },
        ]);
        $promise = $pool->promise();
        $promise->wait();
    }

    /**
     * 检测任务是否结束
     * @return bool
     */
    private function checkThreadIsEnd()
    {
        if (self::$counter < $this->totalPageCount) {
            self::$counter++;
            return false;
        } else {
            return true;
        }
    }


}

執行指令

php think thread

效果

#

以上是講解thinkphp5.1如何實作多執行緒爬蟲的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:csdn.net。如有侵權,請聯絡admin@php.cn刪除