Guzzle同步发送请求

问题描述 投票:2回答:1

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

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

我尝试了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。

->wait()声明之前,我可以看到所有$ promises待定。所以它看起来像是发送异步。在->wait()之后,他们都已经实现了。

这一切都在起作用,减去了性能。所有6个请求不超过2.5到最多3个。

希望有人能提供帮助。

缺口

php asynchronous concurrency guzzle6
1个回答
2
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.