tcp keepalive与http keep-alive

1、长连接
HTTP长连接和短连接,其本质是TCP连接,HTTP是应用层的协议,基于请求/响应模式,而TCP是传输层协议,只有负责传输的这一层才需要建立连接。
长连接情况下,多个HTTP请求可以复用同一个TCP连接,节省TCP连接建立和断开的消耗;

2、http keep-alive
HTTP协议采用请求/应答模式,使用非KeepAlive模式时,每个请求/应答客户和服务器都要新建一个连接,完成之后立即断开TCP连接;使用Keep-Alive模式时,可以复用同一个TCP连接,Keep-Alive功能避免了重新建立TCP连接。
keep-alive常用参数:
keepalive_timeout;
keepalive_requests;

3、tcp keepalive
TCP keepalive用来检测tcp建立连接后,是否有应用报文传输,如果在参数tcpkeepalivetime、tcpkeepaliveprobes之外,则断开TCP连接;
在Linux系统没有全局的选项开启TCP的KeepAlive,必须在TCP的socket中单独开启;
Linux Kernel有三个选项影响到KeepAlive的行为:
1.net.ipv4.tcpkeepaliveintvl = 75
2.net.ipv4.tcpkeepaliveprobes = 9
3.net.ipv4.tcpkeepalivetime = 7200
tcpkeepalivetime表示TCP链接在多少秒之后没有数据报文传输启动探测报文;
tcpkeepaliveintvl单位是也秒,表示前一个探测报文和后一个探测报文之间的时间间隔;
tcpkeepaliveprobes表示探测的次数;
TCP socket也有三个选项和内核对应
TCPKEEPCNT: 覆盖 tcpkeepaliveprobes
TCPKEEPIDLE: 覆盖 tcpkeepalivetime
TCPKEEPINTVL: 覆盖 tcpkeepalive_intvl

4、nginx keepalive与keep-alive
tcp keepalive与http keep-alive

5、nginx网络快速容错
建立连接
tcp_sys_retries
tcp_sysack_retries
关闭连接
fin_timeout
tcp_retries1
tcp_retries2
lingering
6、nginx优化
nginx进程数
worker_rlimit_nofile :最好与ulimit -n的值保持一致
worker_connections:每个进程允许的最多连接数
net.ipv4.tcp_max_tw_buckets:timewait的数量,默认是180000
net.ipv4.tcp_tw_recycle:timewait快速回收
net.ipv4.tcp_tw_reuse:TIME-WAIT sockets重新用于新的TCP连接
net.ipv4.ip_local_port_range:允许系统打开的端口范围
net.ipv4.tcp_synack_retries:内核放弃连接之前发送 SYN+ACK 包的数量
net.ipv4.tcp_keepalive_time :TCP发送keepalive消息的频度

7、补充
upstream中的keepalive的解释
1.The connections parameter sets the maximum number of idle keepalive connections to upstream servers connections
2.When this number is exceeded, the least recently used connections are closed
3.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

猜你喜欢

转载自blog.51cto.com/2198640/2562910