如何在 Laravel 中检查外部 API 限流限制
发布: (2026年1月10日 GMT+8 13:02)
1 min read
原文: Dev.to
Source: Dev.to
思路
- 调用外部 API。
- 检查响应状态码是否为 429(请求过多)。
- 读取速率限制头部(如果有提供)。
- 优雅地处理限流情况。
实现
基本限流检查
use Illuminate\Support\Facades\Http;
public function checkApiThrottle()
{
$response = Http::withOptions([
// Prevent exceptions on HTTP errors
'http_errors' => false,
])->get({API-ENDPOINT});
// Check if API is throttling
if ($response->status() === 429) {
return response()->json([
'throttled' => true,
'message' => 'API rate limit exceeded',
'retry_after' => $response->header('Retry-After'),
], 429);
}
// Read rate‑limit headers (if available)
$rateLimit = [
'limit' => $response->header('X-RateLimit-Limit'),
'remaining' => $response->header('X-RateLimit-Remaining'),
'reset' => $response->header('X-RateLimit-Reset'),
];
return response()->json([
'throttled' => false,
'rate_limit_headers'=> $rateLimit,
'data' => $response->json(),
]);
}
使用最大调用次数的替代方案
use Illuminate\Support\Facades\Http;
public function checkApiThrottle()
{
$maxCall = 10;
$count = 0;
$responses = [];
while ($count status();
$count++;
$responses[] = [
'statusCode' => $statusCode,
'count' => $count,
];
// Stop if the request is not successful (e.g., throttled)
if ($statusCode !== 200) {
break;
}
}
echo "" . print_r($responses, true) . "";
}