这篇文章主要介绍了thinkphp5.1怎么实现多线程爬虫,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。
创建一个cli命令
php think make:command Thread thread
测试能否成功执行
php think thread
文档地址: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('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 < $this->totalPageCount) { self::$counter++; return false; } else { return true; } } }
php think thread
感谢你能够认真阅读完这篇文章,希望小编分享的“thinkphp5.1怎么实现多线程爬虫”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。