Guzzle 发起并发请求
方式一 发起固定数量请求
use GuzzleHttp\Client;
use GuzzleHttp\Promise\Utils;
$client = new Client();
// 启动每个请求但不阻止(block)
$promises = [
'image' => $client->getAsync('http://127.0.0.1:9501/index', ['query' => ['user' => 'image']]),
'png' => $client->getAsync('http://127.0.0.1:9501/index', ['query' => ['user' => 'png']]),
'jpeg' => $client->getAsync('http://127.0.0.1:9501/index', ['query' => ['user' => 'jpeg']]),
'webp' => $client->getAsync('http://127.0.0.1:9501/index', ['query' => ['user' => 'webp']])
];
// 等待请求完成; 如果有请求异常会抛出异常 : RequestException
// 你可以使用 promise 的键来访问每个响应
try {
$result = Utils::unwrap($promises);
foreach ($result as $key => $value) {
$contents = $value->getBody()->getContents();
$this->line("key:" . $key . ";contents:" . $contents);
}
} catch (\Throwable $exception) {
dd($exception);
}
// 等待请求完成,即使其中一些请求已经失败
// {"image":{"state":"fulfilled","value":{}},"jpeg":{"state":"fulfilled","value":{}},"png":{"state":"fulfilled","value":{}},"webp":{"state":"fulfilled","value":{}}}
$responses = Utils::settle($promises)->wait();
foreach ($responses as $key => $value) {
if ($value['state'] === 'fulfilled') {
$contents = $value['value']->getBody()->getContents();
$this->line("key:" . $key . ";contents:" . $contents);
} elseif ($value['state'] === 'rejected') {
$this->line("key:" . $key . "请求失败");
}
}
方式二 发送不确定数量的请求 可以作为接口并发测试
$client = new Client();
$requests = function ($total) {
$uri = 'http://127.0.0.1:9501/landlord';
for ($i = 0; $i < $total; $i++) {
yield new Request('GET', $uri);
}
};
$pool = new Pool($client, $requests(100), [
// 并发发送的最大请求数
'concurrency' => 5,
'fulfilled' => function ($response, $index) {
$this->line(json_encode($response->getBody()->getContents()) . "-index:" . $index);
// this is delivered each successful response
},
'rejected' => function ($reason, $index) {
$this->line($reason->getMessage() . "-index:" . $index);
// this is delivered each failed request
},
]);
// Initiate the transfers and create a promise
$promise = $pool->promise();
// Force the pool of requests to complete.
$promise->wait();
标签:index,请求,批量,value,client,state,Guzzle,key
From: https://www.cnblogs.com/jing1208/p/17406436.html