【问题标题】:Guzzle is sending requests synchronouslyGuzzle 正在同步发送请求
【发布时间】:2018-06-02 07:41:17
【问题描述】:

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

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

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

Checks.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

API\GetProposition.php

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

Webservice.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;
}

我更改了 XML 和一些参数的缩写。结构是这样的,因为我最终必须与多个 API 进行对话,这就是为什么我在两者之间有一个 Web 服务类来完成该 API 所需的所有准备工作。大多数 API 都有多个可以调用的方法/操作,所以我有类似的东西。 API\GetProposition。

-&gt;wait() 语句之前,我可以看到所有 $promises 待处理。所以看起来正在发送异步。在-&gt;wait()之后都已经实现了。

一切正常,减去性能。所有 6 个请求都不会超过 2.5 到最多 3 秒。

希望有人能提供帮助。

尼克

【问题讨论】:

    标签: php asynchronous concurrency guzzle6


    【解决方案1】:

    问题是 $client 对象是随每个请求创建的。导致 curl multi curl 无法知道要使用哪个处理程序。 通过https://stackoverflow.com/a/46019201/7924519找到答案。

    【讨论】:

      猜你喜欢
      • 2016-06-09
      • 2020-02-08
      • 1970-01-01
      • 1970-01-01
      • 2018-02-07
      • 2017-08-28
      • 1970-01-01
      • 1970-01-01
      • 2020-07-14
      相关资源
      最近更新 更多