【发布时间】:2020-02-08 11:23:50
【问题描述】:
我正在尝试使用 Guzzle 发出一些并发请求。代码:
// Imports
use GuzzleHttp\Pool;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request as PSR7Request;
// Part of code that I have problem with
$client = new Client([
'timeout' => 100
]);
$requests = function ($filters, $carbon_date) {
foreach ($filters as $filter) {
yield new PSR7Request('GET', route('filters.run', ['filter' => $filter, 'date' => $carbon_date->format('Y/m/d')]));
Log::debug("Filter Controller Report -> Filter {$filter} fired");
}
};
$result = collect();
$pool = new Pool($client, $requests($filters, $carbon_date), [
'concurrency' => 10,
'fulfilled' => function ($response) use (&$result) {
$result = $result->merge(json_decode($response->getBody(), true));
},
'rejected' => function ($reason, $index) {
Log::error("Filter Controller Report -> A filter has failed", compact('reason'));
}
]);
$pool->promise()->wait();
我正在使用 Laravel,这段代码在控制器中。
正在通过 NGINX+PHP-FPM 提供代码。
每个子请求也记录自己的执行。问题是我在日志中看到了这样的内容:
[2019-10-11 02:10:06] production.DEBUG: Filter Manager -> Filter Filter1 耗时 23 秒
[2019-10-11 02:10:06] production.DEBUG:过滤器控制器报告-> 过滤器 App\Filter\Filter1 已触发
[2019-10-11 02:10:17] production.DEBUG:过滤器管理器->过滤器 Filter2 耗时 11 秒
[2019-10-11 02:10:17] production.DEBUG:过滤器控制器报告-> 过滤器 App\Filter\Filter2 已触发
[2019-10-11 02:10:34] production.DEBUG:过滤器管理器->过滤器 Filter3 耗时 17 秒
[2019-10-11 02:10:34] production.DEBUG:过滤器控制器报告-> 过滤器 App\Filter\Filter3 已触发
[2019-10-11 02:10:51] production.DEBUG:过滤器管理器->过滤器 Filter4 耗时 17 秒
[2019-10-11 02:10:51] production.DEBUG:过滤器控制器报告-> 过滤器 App\Filter\Filter4 已触发
[2019-10-11 02:11:09] production.DEBUG:过滤器管理器->过滤器 Filter5 耗时 18 秒
[2019-10-11 02:11:09] production.DEBUG:过滤器控制器报告-> 过滤器 App\Filter\Filter5 已触发
[2019-10-11 02:11:09] production.DEBUG:过滤器控制器报告-> 过滤器耗时 86 秒
我的过滤器需要 10~20 秒才能运行,所以我预计过滤器的整个请求需要大约 20 秒。您可以看到执行所有请求需要所有时间的总和(86 秒)。
让我确定它没有同时运行的是,Fire 日志出现在实际执行请求之后,这是意料之外的。
我的结果是正确的,但时机不太好。
所以,感谢任何帮助!
【问题讨论】:
-
这看起来不像如何同时使用 Guzzle,你绝对不应该有
yield。您只需要将您从 getAsyc 函数获得的所有承诺放入一个数组中,然后在该数组上调用 wait 。文档在他们的网站上。 -
@AlexBarker 这肯定在他们的网站上。见docs.guzzlephp.org/en/stable/quickstart.html#making-a-request,最后一个例子。