Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
450 views
in Technique[技术] by (71.8m points)

关于guzzle异步请求的耗时问题

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();

执行结果:
image.png

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、如何让异步或者并发请求是完全并行执行呢


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

看你这个打印顺序是异步执行的,是否是源接口方php-fpm进程个数有限制?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...