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
作者最新文章
coreldraw快捷键怎么设置在哪里
2026-11-02 21:39
AO3最新可用链接及中文入口汇总
2026-10-29 13:32
coreldraw怎么插入图片 图片导入步骤
2026-10-27 15:37
coreldraw快捷键冲突 怎么改 自定义按键解决
2026-10-24 08:50
AO3中文界面设置指南与核心功能使用教程
2026-10-14 23:28
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多

































