Skip to content

Instantly share code, notes, and snippets.

@jjsty1e
Created March 21, 2023 01:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jjsty1e/f810f97ba6d7bb9225beb474297a7908 to your computer and use it in GitHub Desktop.
Save jjsty1e/f810f97ba6d7bb9225beb474297a7908 to your computer and use it in GitHub Desktop.
PHP并发请求测试
<?php
// 循环次数
$batch = 10;
// 请求地址
$url = 'http://example.com/';
// 请求头
$headers = [
'Content-Type: application/json',
'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.xxx.rV1UkHJYHe9XXYUXB2kTONVRWpkXOJ6l-tQZkmm_qac'
];
// 请求方法
$method = 'GET';
$mh = curl_multi_init();
$handlers = [];
for ($i =0; $i < $batch; $i++) {
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_HEADER => 0,
CURLOPT_RETURNTRANSFER => true,
]);
$handlers[$i] = $ch;
}
for ($i =0; $i < $batch; $i++) {
curl_multi_add_handle($mh, $handlers[$i]);
}
do {
$status = curl_multi_exec($mh, $active);
if ($active) {
curl_multi_select($mh);
}
} while ($active && $status == CURLM_OK);
foreach ($handlers as $i => $ch) {
$content = curl_multi_getcontent($ch);
curl_multi_remove_handle($mh, $ch);
$cnt = $i+1;
echo "第{$cnt}个请求的结果:\n" . $content . "\n\n";
}
curl_multi_close($mh);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment