插件窝 干货文章 thinkphp5.1怎么实现多线程爬虫

thinkphp5.1怎么实现多线程爬虫

amp class Output function 927    来源:    2024-10-24

创建一个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(null, $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