thinkphp5.1怎么实现多线程爬虫
作者:归人云淡风轻
时间:2023-05-02
浏览:0
创建一个cli命令phpthinkmake:commandThreadthread测试能否成功执行phpthinkthread安装Guzzle类库文档地址:guzzle文档地址(https://guzzle-cn.readthedocs.io/zh_CN/latest/quickstart.html)实现代码
本文目录
创建一个cli命令
php think make:command Thread thread
测试能否成功执行
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 < $this->totalPageCount) {
self::$counter++;
return false;
} else {
return true;
}
}
}执行命令
php think thread
作者最新文章
蛙漫2正版登录入口及漫画更新指南
2026-11-23 10:44
包子漫画官网入口网页版
2026-11-23 10:33
红果短剧电脑登录入口 网页版免费看
2026-11-23 10:24
漫蛙manwa防丢网站2026最新地址
2026-11-22 16:55
AO3官网入口 官方登录页面安全直达
2026-11-21 14:10
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多

































