【问题标题】:How to get Request object in Guzzle?如何在 Guzzle 中获取 Request 对象?
【发布时间】:2017-03-12 03:24:15
【问题描述】:

我需要使用 Guzzle 从我的数据库中检查很多项目。例如,项目数量为 2000-5000。将它全部加载到一个数组中太多了,所以我想将它分成块:SELECT * FROM items LIMIT 100。当最后一个项目发送到 Guzzle 时,接下来会请求 100 个项目。在“已完成”处理程序中,我应该知道哪个项目得到了响应。我看到我们这里有 $index,它指向当前项目的数量。但我无权访问 $items 变量可见的范围。无论如何,如果我什至通过 use($items) 访问它,那么在循环的第二遍中我得到错误的索引,因为 $items 数组中的索引将从 0 开始,而 $index 将> 100。所以,这种方法是行不通的。

    $client = new Client();
    $iterator = function() {
         while($items = getSomeItemsFromDb(100)) {
              foreach($items as $item) {
                   echo "Start item #{$item['id']}";
                   yield new Request('GET', $item['url']);
              }
         }
    };

    $pool = new Pool($client, $iterator(), [
        'concurrency' => 20,
        'fulfilled' => function (ResponseInterface $response, $index) {
            // how to get $item['id'] here?
        },
        'rejected' => function (RequestException $reason, $index) {
            call_user_func($this->error_handler, $reason, $index);
        }
    ]);

    $promise = $pool->promise();
    $promise->wait();

我想如果我可以做类似的事情

$request = new Request('GET', $item['url']);
$request->item = $item;

然后在 'fulfilled' 处理程序中只是为了从 $response 获取 $request - 这将是理想的。但正如我所看到的,没有办法做像 $response->getRequest() 这样的事情。 有关如何解决此问题的任何建议?

【问题讨论】:

  • 你可以返回一个数组yield [ 'request' => new Request('GET', $item['url']), 'id' => $item['id'] ];
  • 你找到解决办法了吗?

标签: php guzzle


【解决方案1】:

很遗憾,在 Guzzle 中无法获得请求。有关详细信息,请参阅响应创建。

但是您可以只返回一个不同的承诺并使用each_limit() 而不是Pool(内部池类只是EachPromise 的包装器)。它是更通用的解决方案,适用于任何类型的 Promise。

也可以看看another example of EachPromise usage for concurrent HTTP request

$client = new Client();
$iterator = function () use ($client) {
    while ($items = getSomeItemsFromDb(100)) {
        foreach ($items as $item) {
            echo "Start item #{$item['id']}";
            yield $client
                ->sendAsync(new Request('GET', $item['url']))
                ->then(function (ResponseInterface $response) use ($item) {
                    return [$item['id'], $response];
                });
        }
    }
};

$promise = \GuzzleHttp\Promise\each_limit(
    $iterator(),
    20,
    function ($result, $index) {
        list($itemId, $response) = $result;

        // ...
    },
    function (RequestException $reason, $index) {
        call_user_func($this->error_handler, $reason, $index);
    }
);

$promise->wait();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-15
    • 1970-01-01
    • 2012-07-22
    • 1970-01-01
    • 1970-01-01
    • 2022-07-13
    • 1970-01-01
    • 2016-02-28
    相关资源
    最近更新 更多