利用GuzzleHttp发起并发请求

利用GuzzleHttp发起并发请求

代码示例

<?php

use GuzzleHttp\Client;
use Psr\Http\Message\ResponseInterface;

require_once __DIR__ . '/vendor/autoload.php';

$client = new Client();


$links = [
    'https://baidu.com?a=1',
    'https://baidu.com?a=2',
    'https://baidu.com?a=3',
    'https://baidu.com?a=4',
    'https://baidu.com?a=5',
    'https://baidu.com?a=6',
    'https://baidu.com?a=7',
    'https://baidu.com?a=8',
    'https://baidu.com?a=9',
    'https://baidu.com?a=10',
    'https://baidu.com?a=11',
    'https://baidu.com?a=12',
    'https://baidu.com?a=13',
    'https://baidu.com?a=14',
    'https://baidu.com?a=15',
    'https://baidu.com?a=16',
    'https://baidu.com?a=17',
    'https://baidu.com?a=18',
    'https://baidu.com?a=19',
    'https://baidu.com?a=20',
    'https://baidu.com?a=21',
    'https://baidu.com?a=22',
];

echo '同步请求', PHP_EOL;
$start_time = microtime(true);

foreach ($links as $index => $link) {
    $resp = $client->get($link);
    $resp->getBody()->getContents();
    echo $index, PHP_EOL;
}


echo 'duration:', microtime(true) - $start_time, PHP_EOL;


echo '并发请求', PHP_EOL;

$start_time = microtime(true);

$request = function (array $links) use ($client) {
    foreach ($links as $key =>  $link) {
	// 利用yield生成回调数组
        yield function () use ($client, $link) {
            return $client->getAsync($link);
        };
    }
};

$pool = new \GuzzleHttp\Pool($client, $request($links), [
    // 请求成功以后的回调参数
    'fulfilled' => function (ResponseInterface $response, $index) {
        echo $index, PHP_EOL;
    },
]);

$pool->promise()->wait();

echo 'duration:', microtime(true) - $start_time, PHP_EOL;

输出结果

同步请求
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
duration:2.3023982048035
并发请求
19
13
3
20
2
9
8
6
16
17
21
11
10
15
1
7
12
14
0
18
4
5
duration:0.67937111854553

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×