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

标签 php asynchronous guzzle reactphp

我正在使用 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/

相关文章:

ssl - drupal 控制台命令上的 GuzzleHttp 异常

php - Doctrine_Pager 在哪里?

php - 从分页中删除当前页面的超链接

javascript - 通用 promise 重试逻辑

c++ - Boost asio async_read_until 然后是 async_read

php - 使用 Guzzle 将更新数据发布到 EventBrite API

php - MySQL:使用 REGEX 从一条记录中提取所有匹配项

php - 如何使用 laravel 添加跳转到功能

c# - C#-异步服务器与同步服务器-套接字

php - 似乎无法使用 php Guzzle 上传大文件