<?php
namespace app\command;
use GuzzleHttp\Client;
use GuzzleHttp\Pool;
use think\console\Command;
use think\console\Input;
use think\console\Output;
class Thread extends Command
{
protected $totalPageCount = 50;
protected static $counter = 1;
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();
}
private function checkThreadIsEnd()
{
if (self::$counter < $this->totalPageCount) {
self::$counter++;
return false;
} else {
return true;
}
}
}