说明 Guzzle库是一套强大的 本文重点演示如何使用 Guzzle 发起多线程请求。 参考 Github 官方用户接口文档 Guzzle 并发请求文档 Laravel LTS 5.1 - Artisan 文档 创建命令 1. 运行命令行创建命令 登录后复制 2. 注册命令 编辑 app/Console/Kernel. Commands\MultithreadingRequest::class,登录后复制 3. 测试下命令 修改 app/Console/Commands/MultithreadingRequest. $this->info('hello');登录后复制 输出: $ 登录后复制 4. 安装 Guzzle composer require guzzlehttp/guzzle "6.2"登录后复制 直接贴代码 一份可运行的代码胜过千言万语呀。 下面代码是 app/Console/Commands/MultithreadingRequest. users); $client = new Client(); $requests = function ($total) use ($client) { foreach ($this->users as $key => $user) { $uri = 'https://api.github.com/users/' . $user; yield function() use ($client, $uri) { return $client->getAsync($uri); }; } }; $pool = new Pool($client, $requests($this->totalPageCount), [ 'concurrency' => $this->concurrency, 'fulfilled' => function ($response, $index){ $res = json_decode($response->getBody()->getContents()); $this->info("请求第 $index 个请求,用户 " . $this->users[$index] . " 的 Github ID 为:" .$res->id); $this->countedAndCheckEnded(); }, 'rejected' => function ($reason, $index){ $this->error("rejected" ); $this->error("rejected reason: " . $reason ); $this->countedAndCheckEnded(); }, ]); // 开始发送请求 $promise = $pool->promise(); $promise->wait(); } public function countedAndCheckEnded() { if ($this->counter totalPageCount){ $this->counter++; return; } $this->info("请求结束!"); }}登录后复制 运行结果: $ 登录后复制 注意请求是同时发送过去的,因为 concurrency并发设置了 7,所以 7 个请求同时发送,只不过接收到返回的时间点不一样。 完。 :beers: :beers: :beers:
09-19 02:07