微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

但是如果我需要池中不同请求的不同选项呢?我想使用池执行GET请求,并将每个响应流式传输到磁盘上的不同文件.有一个接收器选项.但是如何将这个选项的不同值应用于请求?

解决方法:

Rastor’s example几乎是正确的,但如果要为Pool()构造函数提供“选项”,则会错误地实现它.

他错过了here提到的Pool options数组的关键实现.

Guzzle文档说:

When a function is yielded by the iterator, the function is provided
the “request_options” array that should be merged on top of any
existing options, and the function MUST then return a wait-able
promise.

另外,如果你查看我链接的注释下面的Pool()代码,你可以看到Guzzle的Pool调用调用的并给它Pool的“选项”作为参数,正是这样你应该将它应用到你的请求.

正确的优先顺序是

Per-request options > Pool options > Client defaults.

如果你没有将Pool()对象的options数组应用于你的请求对象,你将会遇到严重的错误,例如你尝试制作一个新的游泳池($client,$requests(100),[‘options’=&gt [ ‘超时’=&GT 30.0]]);.如果没有我更正的代码,您的Pool-options将根本不会应用,因为您不支持正确合并池选项,因此最终会丢弃它们.

所以这里是支持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));

但请注意,如果您知道永远不会向新的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));

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐