首页 > 解决方案 > 是否可以通过 HTTP/2 设置 Guzzle + Pool?

问题描述

Guzzle 提供了一种发送并发请求的机制:Pool。我使用了文档中的示例:http ://docs.guzzlephp.org/en/stable/quickstart.html#concurrent-requests 。它工作得很好,发送并发请求,一切都很棒,除了一件事:在这种情况下,Guzzle 似乎忽略了 HTTP/2。

我准备了一个简化的脚本,它向https://stackoverflow.com发送两个请求,第一个是使用 Pool,第二个是一个普通的 Guzzle 请求。只有常规请求通过 HTTP/2 连接。

<?php

include_once 'vendor/autoload.php';

use GuzzleHttp\Client;
use GuzzleHttp\Pool;
use GuzzleHttp\Psr7\Request;

$client = new Client([
    'version' => 2.0,
    'debug' => true
]);

/************************/

$requests = function () {
    yield new Request('GET', 'https://stackoverflow.com');
};
$pool = new Pool($client, $requests());
$promise = $pool->promise();
$promise->wait();

/************************/

$client->get('https://stackoverflow.com', [
    'version' => 2.0,
    'debug' => true,
]);

这是一个输出:https ://pastebin.com/k0HaDWt6 (我用“!!!!!”突出显示了重要部分)

有谁知道 Guzzle 为什么这样做以及如何使 Pool 与 HTTP/2 一起工作?

标签: phpguzzlehttp2

解决方案


发现问题所在:如果传递给请求,则new Client()实际上不接受'version'作为选项创建为. 协议版本必须作为每个请求的选项提供,或者请求必须创建为(或其他)。Poolnew Request()$client->getAsync()->postAsync

请参阅更正后的代码:

...

$client = new Client([
    'debug' => true
]);
$requests = function () {
    yield new Request('GET', 'https://stackoverflow.com', [], null, '2.0');
};
/* OR
$client = new Client([
    'version' => 2.0,
    'debug' => true
]);
$requests = function () use ($client) {
    yield function () use ($client) {
        return $client->getAsync('https://stackoverflow.com');
    };
};
*/
$pool = new Pool($client, $requests());
$promise = $pool->promise();
$promise->wait();

...

推荐阅读