1、对同一个url发起5个异步请求,url耗时10秒,为什么执行过程是每次并行两个请求呢(最终耗时约30秒(10 + 10 + 10))
代码:
$client = new GuzzleHttpClient(['base_uri' => 'xxx']);
$request1 = new GuzzleHttpPsr7Request('GET', '/2.php');
$start = microtime(true);
$promise1 = $client->sendAsync($request1)->then(function ($response) use ($start) {
echo '1: ' . ceil(microtime(true) - $start) . PHP_EOL;
});
$promise2 = $client->sendAsync($request1)->then(function ($response) use ($start) {
echo '2: ' . ceil(microtime(true) - $start) . PHP_EOL;
});
$promise3 = $client->sendAsync($request1)->then(function ($response) use ($start) {
echo '3: ' . ceil(microtime(true) - $start) . PHP_EOL;
});
$promise4 = $client->sendAsync($request1)->then(function ($response) use ($start) {
echo '4: ' . ceil(microtime(true) - $start) . PHP_EOL;
});
$promise5 = $client->sendAsync($request1)->then(function ($response) use ($start) {
echo '5: ' . ceil(microtime(true) - $start) . PHP_EOL;
});
$promise1->wait();
$promise2->wait();
$promise3->wait();
$promise4->wait();
$promise5->wait();
执行结果:
2、使用并发模式请求(耗时跟1一样)
$client = new Client(['base_uri' => 'xxx']);
$promises = [
$client->getAsync('/2.php'),
$client->getAsync('/2.php'),
$client->getAsync('/2.php'),
$client->getAsync('/2.php'),
$client->getAsync('/2.php'),
];
$results = Promiseunwrap($promises);
3、如何让异步或者并发请求是完全并行执行呢
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…