首先TIME_WAIT是TCP协议关闭时候的必经状态,谁主动关闭谁就会到达TIME_WAIT状态!具体可参看我前面的文章(关于Tcp/ip断开连接的4次握手(图文解释))
那么怎么解决Nginx+后线服务出现的TIME_WAIT问题呢?
首先确认的是,默认的Nginx(当前20210720前的版本)默认走的是Tcp短连接,Nginx请求后线服务器后,服务器响应完成后发起close操作。所以此时,后线服务进入到TIME_WAIT状态。
所以,调整TIME_WAIT的数量需要将短连接修改为长连接,每次请求完成后不不关闭Tcp连接。具体配置如下:
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server_zuul {
least_conn;
server 192.168.25.111:8091 weight=1 max_fails=1 fail_timeout=10s;
keepalive 300; //Nginx每个worker连接后端的最大长连接数,而不是整个Nginx的。
}
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
location ^~/SpringCloudServer/ {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-NginX-Proxy true;
proxy_next_upstream off;
proxy_connect_timeout 5;
proxy_http_version 1.1;
proxy_pass http://server_zuul/;
proxy_set_header Connection "";
}
}
}
重点关注一下几个配置项:仅仅增加 keepalive 是不起作用的,需要连同proxy_http_version和proxy_set_header Connection一起设置!!!
## 连接保持时间
keepalive_timeout 65;
## Nginx每个worker连接后端的最大长连接数,而不是整个Nginx的。
keepalive 300;
## HTTP1.1版本才支持长连接,HTTP1.0通过设置请求头也可以,但是不推荐。
proxy_http_version 1.1;
## 请求头 Connection,默认Nginx的HttpProxy模块会设置为close,所以需要清空。禁止服务器关闭连接(并发100%不关闭)
proxy_set_header Connection "";
此时设置完成后,连接将被复用,后线服务器在返回报文后,不在进行close操作。
利用jmeter测试,会发现TIME_WAIT数量快速下降,最低可为0!
但是有时,还是会少量增长,目前暂未研究为何,有知道的大神可以留言!