当前位置: 欣欣网 > 码农

PHP如何并行异步处理HTTP请求

2024-05-19码农

概述

在对接第三方接口时,有些接口可能会比较耗时,为了提高接口调用的效率,可以考虑使用异步请求。通过异步请求,可以在发起接口调用后立即返回结果,而不需要等待接口返回。

正常请求

<?php
/**
 * @desc go.php 描述信息
 * @author Tinywan(ShaoBo Wan)
 * @date 2024/5/18 18:08
 */
declare(strict_types=1);
$url = 'http://127.0.0.1:8888/index/sync';
$timeOne = microtime(true);
foreach (range(1, 100) as $key) {
$list[] = file_get_contents($url);
}
$timeTwo = microtime(true);
echo'[x] [系统调用耗时时间] ' . ($timeTwo - $timeOne) . PHP_EOL;

调用输出,可以看出循环请求100次,总耗时: 37.23

[x] [系统调用耗时时间] 37.230930089951

并发请求

Guzzle是一个PHP的HTTP客户端,用来轻而易举地发送请求,并集成到我们的WEB服务上。

  • 接口简单:构建查询语句、POST请求、分流上传下载大文件、使用HTTP cookies、上传JSON数据等等。

  • 发送同步或异步的请求均使用相同的接口。

  • 使用PSR-7接口来请求、响应、分流,允许你使用其他兼容的PSR-7类库与Guzzle共同开发。

  • 抽象了底层的HTTP传输,允许你改变环境以及其他的代码,如:对cURL与PHP的流或socket并非重度依赖,非阻塞事件循环。

  • 中间件系统允许你创建构成客户端行为。

  • 这里可以使用 Promise 和异步请求来同时发送多个请求。

    安装

    compsoer require guzzlehttp/guzzle

    伪代码

    <?php
    /**
     * @desc go.php 
     * @author Tinywan(ShaoBo Wan)
     * @date 2024/5/18 18:08
     */

    declare(strict_types=1);
    require_once__DIR__ . '/../vendor/autoload.php';
    useGuzzleHttp\Client;
    useGuzzleHttp\Promise;
    $requestData = [
    'username' => '开源技术小栈',
    'age' => 24
    ];
    $url = 'http://127.0.0.1:8888/index/sync';
    $header = [
    'Authorization' => 'Bearer xxxxxxxxxxxx'
    ];
    $timeOne = microtime(true);
    $client = new Client(['verify' => false]);
    for ($i = 0; $i < 100; $i++) {
    $promises[$i] = $client->postAsync($url, ['headers' => $header, 'json' => $requestData]);
    }
    $responses = Promise\Utils::unwrap($promises);
    foreach ($responses as $key => $response) {
    echo'【响应状态码】 : ' . $response->getStatusCode() . "\n";
    }
    $timeTwo = microtime(true);
    echo'[x] [系统调用耗时时间] ' . ($timeTwo - $timeOne) . PHP_EOL;





    调用输出,可以看出循环请求 100 次,总耗时: 10.41

    【响应状态码】 : 200
    ....
    【响应状态码】 : 200
    [x] [系统调用耗时时间] 10.412175893784

    更多了解guzzlephp官方文档: https://docs.guzzlephp.org/en/stable/quickstart.html