Nginx-Keepalive

在我们选在Nginx作为http请求的负载均衡时候,整个请求的流向是:上游服务 --> Nginx -->下游服务。

当请求量级过大的时候,我们一般都会在上游服务请求下游服务的时候在client中打开长连接设置:headers.add(new BasicHeader("Connection", "Keep-Alive"))。在Nginx侧不需要做任何措施。默认情况下,Nginx已经自动开启了对上游连接的keep-alive支持。

此时整个请求的链路的状态:

  • 从上游服务到Nginx的连接是长连接
  • 从Nginx到下游服务的连接是短连接

默认情况下 Nginx 访问后端都是用的短连接(HTTP1.0),一个请求来了,Nginx 新开一个端口和后端建立连接,请求结束连接回收。

如果需要Nginx到下游服务也是长连接的时候需要两步设置:

  1. 在Nginx的Server.conf中配置:

    server {
        …
        location /xxx/ {
            proxy_pass http://http_xxx;
            proxy_http_version 1.1;
            proxy_set_header Connection "";
            …
        }
    }
    

此时说明从Nginx upsteam下游请求的时候是默认的长连接。

  1. 在upsteam.conf中设置keepalive connections:

    upstream http_xxx {
        server 127.0.0.1:8080;
        keepalive 256;
    }
    

    这个是激活Nignx到下游服务连接缓存数。
    官方解释:

    Activates the cache for connections to upstream servers.(将Nginx与要有服务的连接缓存下来)
    The connections parameter sets the maximum number of idle keepalive connections to upstream servers that are preserved in the cache of each worker process. When this number is exceeded, the least recently used connections are closed.(该connections参数设置在每个工作进程的缓存中保留与下游服务的最大空闲keepalive连接数。超过此数量时,将关闭最近最少使用的连接。)
    It should be particularly noted that the keepalive directive does not limit the total number of connections to upstream servers that an nginx worker process can open. The connections parameter should be set to a number small enough to let upstream servers process new incoming connections as well.(应特别注意的是,该keepalive指令不限制nginx工作进程可以打开的下游服务的连接总数。该connections参数应设置为足够小的数字,以允许下游服务处理新的传入连接。)
    

    需要注意的是:keepalive 这个参数一定要小心设置,尤其对于QPS比较高的场景,需要先做一下估算,根据QPS和平均响应时间大体能计算出需要的长连接的数量。比如前面10000 QPS和100毫秒响应时间就可以推算出需要的长连接数量大概是1000. 然后将keepalive设置为这个长连接数量的10%到30%。

    还有还有一些长连接设置的参数:keepalive_timeout、keepalive_requests

此刻,完整的长连接服务就完整的建立起来了。
如果想查看请求是长连接、短连接可以通过抓包来查看完整的链路请求。

容易混淆的概念:
TCP的keep alive和HTTP的Keep-alive

  • TCP的keep alive是检查当前TCP连接是否活着;
  • HTTP的Keep-alive是要让一个TCP连接活久点,请求在一个tcp链路上传输,减少握手、分手协议,节省性能。

并且它们是不同层次的概念TCP是传输层协议,而HTTP是应用层协议,HTTP协议是建立在TCP协议基础之上的。

你可能感兴趣的:(Nginx-Keepalive)