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

创建一个cli命令

php think make:command Thread thread

测试能否成功执行

ViiTor实时翻译 ViiTor实时翻译

AI实时多语言翻译专家!强大的语音识别、AR翻译功能。

ViiTor实时翻译 116 查看详情 ViiTor实时翻译

php think thread

安装Guzzle类库

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

实现代码

setName('thread');        // 设置参数    }    protected function execute(Input $input, Output $output)    {        $client = new Client();        $requests = function ($total) use ($client) {            foreach (range(1, $total) as $r) {                $uri = 'https://apinew.juejin.im/content_api/v1/short_msg/detail';                yield function () use ($client, $uri) {                    return $client->postAsync($uri, [                        'verify' => false,                        'json' => [                            'msg_id' => '6845185452727599118'                        ]                    ]);                };            }        };        $pool = new Pool($client, $requests($this->totalPageCount), [            'concurrency' => $this->threads,            // 请求成功            'fulfilled' => function ($response, $index) use ($output) {                $res = $response->getBody()->getContents();                $output->writeln($res);                $output->writeln("正在执行第{$index}个·····");                if ($this->checkThreadIsEnd() == true) {                    $output->writeln("------------请求结束---------");                    return false;                }            },            // 请求失败            'rejected' => function ($reason, $index) use ($output) {                $output->writeln("执行失败,{$reason}");            },        ]);        $promise = $pool->promise();        $promise->wait();    }    /**     * 检测任务是否结束     * @return bool     */    private function checkThreadIsEnd()    {        if (self::$counter totalPageCount) {            self::$counter++;            return false;        } else {            return true;        }    }}

执行命令

php think thread

以上就是thinkphp5.1怎么实现多线程爬虫的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/306729.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年11月5日 03:20:24
下一篇 2025年11月5日 03:22:18

相关推荐

发表回复

登录后才能评论
关注微信