gpt4 book ai didi

php - Guzzle:使用 Guzzle 的 Pool:batch() 和 `sink` 选项并行下载文件

转载 作者:行者123 更新时间:2023-12-02 06:32:13 32 4
gpt4 key购买 nike

您可以使用 Guzzle 的 Pool:batch() 方法并行执行 http 请求。它允许您使用第三个参数中的 options 键为请求设置默认选项。

但是如果我需要为池中的不同请求提供不同的选项怎么办?我想使用池执行 GET 请求并将每个响应流式传输到磁盘上的不同文件。有一个 sink 选项。但是如何将此选项的不同值应用于请求?

最佳答案

Rastor's example几乎是正确的,但如果您想为 Pool() 构造函数提供“选项”,则它的实现不正确。

他缺少提到的池选项数组的关键实现 here .

Guzzle 文档说:

When a function is yielded by the iterator, the function is providedthe "request_options" array that should be merged on top of anyexisting options, and the function MUST then return a wait-ablepromise.

此外,如果您查看我链接到的评论下方的 Pool() 代码,您可以看到 Guzzle 的 Pool 调用可调用对象并将 Pool 的“选项”作为参数提供给它,准确地说这样您就应该将其应用于您的请求。

正确的优先顺序是

Per-request options > Pool options > Client defaults.

如果您不将 Pool() 对象的选项数组应用于您的请求对象,您最终会遇到严重的错误,例如如果您尝试创建一个 new Pool($client , $requests(100), ['options'=>['timeout'=>30.0]]);。如果没有我更正的代码,您的池选项将根本不会应用,因为不支持正确合并池选项,因此最终只是丢弃它们。

下面是支持 Pool() 选项的正确代码:

<?php

$client = new \GuzzleHttp\Client();

$requests = function ($total) use ($client) {
for ($i = 0; $i < $total; $i++) {
$url = "domain.com/picture/{$i}.jpg";
$filepath = "/tmp/{$i}.jpg";

yield function($poolOpts) use ($client, $url, $filepath) {
/** Apply options as follows:
* Client() defaults are given the lowest priority
* (they're used for any values you don't specify on
* the request or the pool). The Pool() "options"
* override the Client defaults. And the per-request
* options ($reqOpts) override everything (both the
* Pool and the Client defaults).
* In short: Per-Request > Pool Defaults > Client Defaults.
*/
$reqOpts = [
'sink' => $filepath
];
if (is_array($poolOpts) && count($poolOpts) > 0) {
$reqOpts = array_merge($poolOpts, $reqOpts); // req > pool
}

return $client->getAsync($url, $reqOpts);
};
}
};

$pool = new Pool($client, $requests(100));

但是请注意,如果您知道永远不会向您的 new Pool() 添加任何选项,则您不必支持 Pool() 选项构造函数。在这种情况下,您可以只看the official Guzzle docs。举个例子。

官方例子如下:

// Using a closure that will return a promise once the pool calls the closure.
$client = new Client();

$requests = function ($total) use ($client) {
$uri = '127.0.0.1:8126/guzzle-server/perf';
for ($i = 0; $i < $total; $i++) {
yield function() use ($client, $uri) {
return $client->getAsync($uri);
};
}
};

$pool = new Pool($client, $requests(100));

关于php - Guzzle:使用 Guzzle 的 Pool:batch() 和 `sink` 选项并行下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31857143/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com