In the example code, you're creating a new GuzzleHttpClient
instance for every request you want to make. This might not seem important, however, during instantiation of GuzzleHttpClient
it will set a default handler if none is provided. (This value is then passed down to any request being sent through the Client, unless it is overridden.)
Note: It determines the best handler to use from this function. Though, it'll most likely end up defaulting to curl_mutli_exec
.
What's the importance of this? It's the underlying handler that is responsible for tracking and executing multiple requests at the same time. By creating a new handler every time, none of your requests are properly being grouped up and ran together. For some more insight into this take a gander into the curl_multi_exec
docs.
So, you kind of have two ways of dealing with this:
Pass through the client through to the iterator:
$client = new GuzzleHttpClient(['timeout' => 20]);
$iterator = function () use ($client) {
$index = 0;
while (true) {
if ($index === 10) {
break;
}
$url = 'http://localhost/wait/5/' . $index++;
$request = new Request('GET', $url, []);
echo "Queuing $url @ " . (new Carbon())->format('Y-m-d H:i:s') . PHP_EOL;
yield $client
->sendAsync($request)
->then(function (Response $response) use ($request) {
return [$request, $response];
});
}
};
$promise = GuzzleHttpPromiseeach_limit(
$iterator(),
10, /// concurrency,
function ($result, $index) {
/** @var GuzzleHttpPsr7Request $request */
list($request, $response) = $result;
echo (string)$request->getUri() . ' completed ' . PHP_EOL;
}
);
$promise->wait();
or create the handler elsewhere and pass it to the client: (Though I'm not sure why you'd do this, but it's there!)
$handler = GuzzleHttpHandlerStack::create();
$iterator = function () use ($handler) {
$index = 0;
while (true) {
if ($index === 10) {
break;
}
$client = new Client(['timeout' => 20, 'handler' => $handler])
$url = 'http://localhost/wait/5/' . $index++;
$request = new Request('GET', $url, []);
echo "Queuing $url @ " . (new Carbon())->format('Y-m-d H:i:s') . PHP_EOL;
yield $client
->sendAsync($request)
->then(function (Response $response) use ($request) {
return [$request, $response];
});
}
};
$promise = GuzzleHttpPromiseeach_limit(
$iterator(),
10, /// concurrency,
function ($result, $index) {
/** @var GuzzleHttpPsr7Request $request */
list($request, $response) = $result;
echo (string)$request->getUri() . ' completed ' . PHP_EOL;
}
);
$promise->wait();
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…