Guzzle 正在同步发送请求

nic*_*ktc 4 php concurrency asynchronous guzzle6

我正在使用 Guzzle 来使用 SOAP API。我必须提出 6 个请求,但将来这甚至可能是不确定数量的请求。

问题是请求是同步发送的,而不是异步的。每个请求本身需要 +-2.5 秒。当我并行发送所有 6 个请求时(至少这就是我正在尝试的),需要 +- 15 秒。

我尝试了 Guzzle 上的所有示例,其中一个带有 $promises 的固定数组,甚至是池(我最终需要它)。当我将所有内容放入 1 个文件(功能性)时,我设法将总时间恢复到 5-6 秒(这可以吗?)。但是,当我以某种方式将所有内容放入对象和函数中时,我做了一些事情,让 Guzzle 决定再次同步它们。

检查.php:

    public function request()
    {
        $promises = [];
        $promises['requestOne'] = $this->requestOne();
        $promises['requestTwo'] = $this->requestTwo();
        $promises['requestThree'] = $this->requestThree();
        // etc

        // wait for all requests to complete
        $results = \GuzzleHttp\Promise\settle($promises)->wait();

        // Return results
        return $results;
    }

    public function requestOne()
    {
         $promise = (new API\GetProposition())
            ->requestAsync();
         return $promise;
    }            

    // requestTwo, requestThree, etc
Run Code Online (Sandbox Code Playgroud)

API\GetProposition.php

public function requestAsync()
{
    $webservice = new Webservice();
    $xmlBody = '<some-xml></some-xml>';
    return $webservice->requestAsync($xmlBody, 'GetProposition');
}
Run Code Online (Sandbox Code Playgroud)

网络服务.php

public function requestAsync($xmlBody, $soapAction)
{
    $client = new Client([
        'base_uri' => 'some_url',
        'timeout'  => 5.0
    ]);

    $xml = '<soapenv:Envelope>
       <soapenv:Body>
          '.$xmlBody.'
       </soapenv:Body>
    </soapenv:Envelope>';

    $promise = $client->requestAsync('POST', 'NameOfService', [
        'body'    => $xml,
        'headers' => [
            'Content-Type' => 'text/xml',
            'SOAPAction'   => $soapAction, // SOAP Method to post to
        ],
    ]);

    return $promise;
}
Run Code Online (Sandbox Code Playgroud)

我更改了 XML 和一些缩写参数。结构是这样的,因为我最终不得不讨论多个 API,这就是为什么我在中间有一个 webservice 类来完成该 API 所需的所有准备工作。大多数 API 都有多种可以调用的方法/操作,这就是为什么我有类似的东西。API\GetProposition。

在声明之前->wait()我可以看到所有 $promises 待处理。所以看起来正在异步发送。当->wait()它们全部实现之后。

除了性能之外,一切都正常。所有 6 个请求所花费的时间不会超过 2.5 秒到最多 3 秒。

希望有人能帮忙。

缺口

nic*_*ktc 5

问题是 $client 对象是随着每个请求而创建的。导致卷曲多卷曲无法知道要使用哪个处理程序。通过/sf/answers/3221344101/找到答案。