我没有找到太多关于concurrency
选项中Pool
.
如果这是可以在服务器上打开的 TCP 套接字数量,那么问题是“我可以使用多少并发来更快地处理请求?”。
我有这个使用的例子Pool
:
// I am using Laravel, this is basically retrieving entities from DB
$exchangers = Exchanger::all();
$client = new Guzzlelient();
$requests = [];
foreach ($exchangers as $exchanger)
{
$requests[$exchanger->id] = new Request('GET', $exchanger->xml_feed_url);
}
$pool = new Pool($client, $requests, [
'concurrency' => 5,
'options' => [
'verify' => false
],
'fulfilled' => function ($response, $index) {
echo "fulfilled: " . $index."\n";
},
'rejected' => function ($reason, $index) {
echo "rejected: " . $index. "\n";
},
]);
// Initiate the transfers and create a promise
$promise = $pool->promise();
// Force the pool of requests to complete.
$promise->wait();
在并发设置为 5 的情况下,访问约 20 个站点大约需要 10 秒。
现在我在想,“好吧,这是套接字的数量。套接字〜端口。我有 65535 个端口。酷,为什么不设置并发 50,我应该在一秒钟左右获得所有结果?”。很好,我将其设置为 50,然后...花了 8 秒。然而一小时前,结果是 18 秒 vs 24 秒(对于 50 个并发,所以速度更慢)。
所以问题是:
- 如何确定我可以使用哪种并发来优化流程并使其尽可能更快?
- 到底什么是并发?
这正是您所期望的。您发送 X 个并发请求,但仅concurrency
请求同时发送。每当一个请求完成时,另一个请求就会排队(源代码 https://github.com/guzzle/promises/blob/master/src/EachPromise.php#L119)
这是在源代码中完成的方法:
private function refillPending()
{
if (!$this->concurrency) {
// Add all pending promises.
while ($this->addPending() && $this->advanceIterator());
return;
}
// Add only up to N pending promises.
$concurrency = is_callable($this->concurrency)
? call_user_func($this->concurrency, count($this->pending))
: $this->concurrency;
$concurrency = max($concurrency - count($this->pending), 0);
// Concurrency may be set to 0 to disallow new promises.
if (!$concurrency) {
return;
}
// Add the first pending promise.
$this->addPending();
// Note this is special handling for concurrency=1 so that we do
// not advance the iterator after adding the first promise. This
// helps work around issues with generators that might not have the
// next value to yield until promise callbacks are called.
while (--$concurrency
&& $this->advanceIterator()
&& $this->addPending());
}
每次请求完成时都会调用此方法(函数step
设置为在每次成功或失败回调后调用)。
然而,作为一般规则,更多并不总是意味着更好,因为您可能会在其他地方遇到其他限制,例如操作系统套接字或 ISP 速率限制或远程服务器速率限制(如果所有请求都发送到同一服务器)。在大多数情况下,最佳值是通过反复试验找到的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)