在Nginx中实现HTTP请求的重试功能可以通过多种方式配置,主要取决于你的具体使用场景。以下是几种常见的配置方法:
这是最常用的HTTP请求重试配置方式,适用于Nginx作为反向代理时:
location / {
proxy_pass http://backend;
proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
proxy_next_upstream_timeout 5s;
proxy_next_upstream_tries 3;
}
参数说明:
- proxy_next_upstream
:指定在什么情况下重试请求
- error
:与服务器建立连接、传递请求或读取响应头时出错
- timeout
:与服务器建立连接、传递请求或读取响应头时超时
- invalid_header
:服务器返回空或无效响应
- http_500
/http_502
/http_503
/http_504
:服务器返回这些状态码时重试
- proxy_next_upstream_timeout
:重试超时时间限制
- proxy_next_upstream_tries
:最大重试次数(包括初始请求)
upstream backend {
server backend1.example.com max_fails=3 fail_timeout=30s;
server backend2.example.com max_fails=3 fail_timeout=30s;
}
参数说明:
- max_fails
:在fail_timeout
时间内失败多少次后标记服务器不可用
- fail_timeout
:服务器被标记为不可用的时间,以及统计失败次数的窗口时间
location / {
proxy_pass http://backend;
error_page 502 503 504 = @retry;
}
location @retry {
proxy_pass http://backend;
proxy_next_upstream error timeout http_502 http_503 http_504;
proxy_next_upstream_tries 2;
}
location / {
access_by_lua_block {
local max_retries = 3
local retry_delay = 1 -- seconds
for i = 1, max_retries do
local res = ngx.location.capture("/internal-proxy")
if res.status == ngx.HTTP_OK then
ngx.exit(res.status)
end
if i < max_retries then
ngx.sleep(retry_delay)
end
end
ngx.exit(res.status)
}
}
location /internal-proxy {
internal;
proxy_pass http://backend;
}
以上配置可以根据你的具体需求进行调整和组合使用。