Nginx 熔断机制

📅 发布时间:2026/7/16 14:33:28 👁️ 浏览次数:
Nginx 熔断机制
Nginx 的熔断机制主要基于Upstream 模块实现其核心逻辑是“当某个后端节点在指定时间内连续失败达到一定次数则暂时将其剔除不再转发请求直到超时后尝试恢复。”这是一种被动式、节点级的熔断保护两个关键参数参数含义作用max_fails最大失败次数在fail_timeout时间内如果失败次数达到此值触发熔断。fail_timeout熔断时长/检测周期1. 计数窗口统计失败次数的时间范围。2. 熔断时长节点被剔除后多久不转发请求之后会尝试探测。场景描述后端有 3 台服务器如果在 30秒 内某台服务器连续失败 3次则将其熔断 30秒期间请求自动转发给其他健康节点。nginx的配置信息http{# 定义上游服务器组upstream backend_pool{# 策略30秒内失败3次 - 熔断30秒server192.168.1.10:8080max_fails3fail_timeout30s;server192.168.1.11:8080max_fails3fail_timeout30s;server192.168.1.12:8080max_fails3fail_timeout30s;# 可选设置负载均衡算法 (默认是轮询)# least_conn;}server{listen80;server_name api.example.com;location /{proxy_pass http://backend_pool;# 【关键】定义什么是“失败”# 默认包含连接错误、超时、500/502/503/504# 这里显式声明遇到 502, 503, 504 或超时时算作一次失败并尝试转发下一台proxy_next_upstream errortimeouthttp_502 http_503 http_504;# 限制重试次数防止所有节点都忙时无限重试拖垮系统proxy_next_upstream_tries2;# 设置较短的超时时间以便快速触发熔断判定proxy_connect_timeout 2s;proxy_send_timeout 5s;proxy_read_timeout 5s;# 隐藏后端错误信息统一返回友好提示proxy_intercept_errors on;error_page502503504/50x.html;}location/50x.html{root /usr/share/nginx/html;internal;}}}针对不同接口设置不同熔断策略如果 /api/slow 接口本身就很慢容易误触熔断可以单独配置 upstream# 普通接口严格熔断upstream normal_api{server10.0.0.1:8080max_fails2fail_timeout10s;}# 慢接口宽松熔断 (允许失败更多次容忍更长时间)upstream slow_api{server10.0.0.1:8080max_fails5fail_timeout60s;}server{location /api/normal{proxy_pass http://normal_api;}location /api/slow{proxy_read_timeout 30s;# 延长超时proxy_pass http://slow_api;}}配合 proxy_cache 实现“熔断降级”当后端全部熔断时直接返回缓存的静态页面而不是报错location /{proxy_pass http://backend_pool;# 开启缓存proxy_cache my_cache;proxy_cache_valid20010m;# 【高级技巧】当后端所有节点都不可用 (502/503/504) 时直接使用过期缓存或返回特定内容proxy_cache_use_stale errortimeoutupdating http_502 http_503 http_504;# 如果没有缓存且后端挂了返回友好的降级页面error_page502503504fallback;}location fallback{default_type text/html;return200系统维护中请稍后再试... (降级模式);}