我正在使用 guzzle 发送一些请求:
$response = $this->client->request(new SomeObject());
使用下面的类
...
public function request(Request $request)
{
return $this->requestAsync($request)->wait();
}
// Here I'm using Guzzle Async, but I can remove that is needed
public function requestAsync(Request $request)
{
$promise = $this->http->requestAsync($request->getMethod(), $request->getUri());
$promise = $promise->then(
function (ResponseInterface $response) use ($request) {
return $response;
}
);
return $promise;
}
...
我想使用 ReactPHP 在 foreach 循环中一次发送多个请求:
$requests = [];
foreach ($data as $value) {
$requests[] = $this->client->request(new SomeObject());
}
// pass $requests to ReactPHP here and wait on the response
有什么想法吗?
最佳答案
首先,您不需要 ReactPHP 即可通过 Guzzle 使用并行 HTTP 请求。 Guzzle 本身提供了此功能(如果您使用 cURL 处理程序,这是默认的)。
例如:
$promises = [];
foreach ($data as $value) {
$promises[] = $guzzleClient->getAsync(/* some URL */);
}
// Combine all promises
$combinedPromise = \GuzzleHttp\Promise\all($promises)
// And wait for them to finish (all requests are executed in parallel)
$responses = $combinedPromise->wait();
如果您仍然想将 Guzzle 与 ReactPHP 事件循环一起使用,那么不幸的是,没有直接的解决方案。你猫看看https://github.com/productsupcom/guzzle-react-bridge (我是开发者,所以请随意提问)。
关于php - ReactPHP 如何一次发送多个请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52376076/