1. 程式人生 > 其它 >nginx重試機制proxy_next_upstream

nginx重試機制proxy_next_upstream

https://blog.csdn.net/weixin_34388207/article/details/93050741

nginx作為反向代理伺服器,後端RS有多臺伺服器,上層通過一定機制保證容錯和負載均衡。

nginx的重試機制就是容錯的一種

官方連結:http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_next_upstream

proxy_next_upstream error | timeout | invalid_header | http_500 | http_502 | http_503 | http_504 | http_403 | http_404 | http_429 | non_idempotent | off ...;
Default:    proxy_next_upstream error timeout;
Context:    http, server, location

指定應將請求傳遞到下一個伺服器的情況:
error             # 與伺服器建立連線,向其傳遞請求或讀取響應頭時發生錯誤;
timeout           # 在與伺服器建立連線,向其傳遞請求或讀取響應頭時發生超時;
invalid_header    # 伺服器返回空的或無效的響應;
http_500          # 伺服器返回程式碼為500的響應;
http_502          # 伺服器返回程式碼為502的響應;
http_503          # 伺服器返回程式碼為503的響應;
http_504          # 伺服器返回程式碼504的響應;
http_403          # 伺服器返回程式碼為403的響應;
http_404          # 伺服器返回程式碼為404的響應;
http_429          # 伺服器返回程式碼為429的響應(1.11.13);
non_idempotent    # 通常,請求與 非冪等 方法(POST,LOCK,PATCH)不傳遞到請求是否已被髮送到上游伺服器(1.9.13)的下一個伺服器; 啟用此選項顯式允許重試此類請求;
off               # 禁用將請求傳遞給下一個伺服器。

下面還有一個引數影響重試次數,0表示不限制。:

Syntax:     proxy_next_upstream_tries number;
Default:    proxy_next_upstream_tries 0;
Context:    http, server, location

舉例如下:

upstream app-proxy {
    server 192.168.5.100:8080;
    server 192.168.5.101:8080;
    check interval=2000 rise=1 fall=3 timeout=3000 type=http;
    check_keepalive_requests 1;
#    check_http_send "HEAD /status/status.html HTTP/1.1\r\n\r\n"; 
    check_http_send "GET /status/status.html HTTP/1.1\r\nConnection: close\r\nHost: localhost\r\n\r\n"; 
    check_http_expect_alive http_2xx http_3xx;
}

location / {
      proxy_pass         http://app-proxy;
      proxy_next_upstream error timeout http_500 http_502 http_503 http_504;
      proxy_next_upstream_tries 3;
      proxy_connect_timeout 60s;
      proxy_read_timeout 60s;
      proxy_send_timeout 60s;
      proxy_pass_request_headers      on;
      proxy_set_header   Host             $host:$server_port;
      proxy_set_header   X-Real-IP        $remote_addr;
      proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
      set $domain default;