laravel框架中使用GuzzleHttp併發請求多個接口

Guzzle是一個PHP的HTTP客戶端,用來輕而易舉地發送請求,並集成到我們的WEB服務上。

  • 接口簡單:構建查詢語句、POST請求、分流上傳下載大文件、使用HTTP cookies、上傳JSON數據等等。
  • 發送同步或異步的請求均使用相同的接口。 使用PSR-7接口來請求、響應、分流,允許你使用其他兼容的PSR-7類庫與Guzzle共同開發。
  • 抽象了底層的HTTP傳輸,允許你改變環境以及其他的代碼,如:對cURL與PHP的流或socket並非重度依賴,非阻塞事件循環。
  • 中間件系統允許你創建構成客戶端行爲。
use GuzzleHttp\Client;
use GuzzleHttp\Promise;


class MyService extends BasicService
{
    public function getCityListOther()
    {
        $url = Common::loadConfig('finance', 'getCityUrl', true);
        $client = new Client(['connect_timeout' => 3, 'timeout' => 5,]);

        $promises = [
            'buying'  => $client->getAsync($url.'?businessType=1'),
            'license' => $client->getAsync($url.'?businessType=2'),
            'deliver' => $client->getAsync($url.'?businessType=3'),
        ];
        $results = Promise\unwrap($promises);

        $myInfo1 = (string)$results['buying']->getBody();
        $myInfo2 = (string)$results['license']->getBody();
        $myInfo3 = (string)$results['deliver']->getBody();

        $buyingArr = json_decode($myInfo1, true);
        $licenseArr = json_decode($myInfo2, true);
        $deliverArr = json_decode($myInfo3, true);
        var_dump($buyingArr,$licenseArr,$deliverArr);
        }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章