如何一次发送多个请求ReactPHP?

时间:2018-09-17 21:44:03

标签: php asynchronous guzzle reactphp

我正在用枪口发送一些请求:

$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

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

首先,您不需要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();

如果您仍然想在ReactPHP事件循环中使用Guzzle,那么不幸的是,没有简单的解决方案。您可以看看https://github.com/productsupcom/guzzle-react-bridge(我是开发人员,请随时提问)。