限制同时在途的请求
将待取的地址放入队列,另设正在运行的句柄集合。示例最多同时处理三个请求。只要某个句柄结束,就移除它并取下一条,无须等第一组全部结束。请先用自己有权调用的接口验证,示例地址仅用来说明列表形态。
<?php
function fetchConcurrently(array $urls, int $limit = 3): array
{
if ($limit < 1) {
throw new InvalidArgumentException('limit must be positive');
}
$urls = array_values($urls);
$next = 0;
$active = [];
$results = [];
$multi = curl_multi_init();
$fill = function () use ($urls, $limit, $multi, &$next, &$active): void {
while ($next < count($urls) && count($active) < $limit) {
$handle = curl_init($urls[$next]);
curl_setopt_array($handle, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 3,
CURLOPT_TIMEOUT => 8,
]);
if (curl_multi_add_handle($multi, $handle) !== CURLM_OK) {
throw new RuntimeException('Could not enqueue request');
}
$active[spl_object_id($handle)] = [$handle, $next++];
}
};
try {
$fill();
while ($active) {
if (curl_multi_exec($multi, $running) !== CURLM_OK) {
throw new RuntimeException('Could not advance requests');
}
while ($info = curl_multi_info_read($multi)) {
$handle = $info['handle'];
$key = spl_object_id($handle);
[, $index] = $active[$key];
$results[$index] = [
'status' => curl_getinfo($handle, CURLINFO_RESPONSE_CODE),
'transport_error' => $info['result'],
'body' => curl_multi_getcontent($handle),
];
curl_multi_remove_handle($multi, $handle);
unset($active[$key]);
}
$beforeFill = $next;
$fill();
if ($active && $next === $beforeFill && $running > 0) {
if (curl_multi_select($multi, 0.5) === -1) {
usleep(10000);
}
}
}
} finally {
foreach ($active as [$handle]) {
curl_multi_remove_handle($multi, $handle);
}
curl_multi_close($multi);
}
ksort($results);
return $results;
}
看懂每个请求的结果
多句柄调用返回正常只表示驱动循环没有整体出错。单个请求的连接错误或超时,请看 transport_error;连接成功后,仍要根据 status 判断业务请求是否可用。例如 HTTP 404 是对端返回的状态,不能计成连接失败。
如何确认补位真的生效
用四个测试地址,其中一个延迟返回,其余快速返回。并发上限设为三,观察第四个请求是否在首个快请求完成后启动;再确认输出仍按输入顺序排列。调整上限前先看对端限流、错误率和尾部耗时。