http1.0 vs http1.1
Connection: keep-alive
Connection: close
HTTP/1.1 200 OK
Connection: Keep-Alive
Content-Encoding: gzip
Content-Type: text/html; charset=utf-8
Date: Thu, 11 Aug 2016 15:23:13 GMT
Keep-Alive: timeout=5, max=1000
Last-Modified: Mon, 25 Jul 2016 04:32:39 GMT
Server: Apache
so_keepalive
SO_KEEPALIVE
Linux has built-in support for keepalive. You need to enable TCP/IP networking in order to use it. You also need procfs support and sysctl support to be able to configure the kernel parameters at runtime.
The procedures involving keepalive use three user-driven variables:
tcp_keepalive_time
the interval between the last data packet sent (simple ACKs are not considered data) and the first keepalive probe; after the connection is marked to need keepalive, this counter is not used any further
tcp_keepalive_intvl
the interval between subsequential keepalive probes, regardless of what the connection has exchanged in the meantime
tcp_keepalive_probes
the number of unacknowledged probes to send before considering the connection dead and notifying the application layer
sysctl -a | grep tcp.keep
net.ipv4.tcp_keepalive_intvl = 75
net.ipv4.tcp_keepalive_probes = 9
net.ipv4.tcp_keepalive_time = 7200
默认tcp_keepalive_time 的值为7200s(2小时) ,超时时间(开启keepalive的闲置时长)
默认tcp_keepalive_intvl 的值为75s,tcp检查间隔时间(keepalive探测包的发送间隔)
默认tcp_keepalive_probes 的值为9 ,tcp检查次数(如果对方不予应答,探测包的发送次数)
nginx 相关配置
## Module ngx_http_core_module
keepalive_disable
keepalive_requests
keepalive_time
keepalive_timeout
listen so_keepalive=30m::10
## Module ngx_http_upstream_module
keepalive
keepalive_requests
keepalive_time
keepalive_timeout
## Module ngx_http_proxy_module
proxy_socket_keepalive
proxy_http_version 1.1; # 使用HTTP/1.1协议
proxy_set_header Connection "te"; # 设置Connection头
proxy_set_header TE "trailers"; # 指定希望接受尾部信息
proxy_pass_trailers on; # 启用尾部转发
proxy_pass http://backend_server; # 转发请求到后端服务器
somaxconn
## linux conf
net.core.netdev_max_backlog = 16384
net.ipv4.tcp_max_syn_backlog = 8096
net.core.somaxconn = 32768
## nginx conf
listen 80 backlog=1024;
backlog=积压
backlog 参数描述的是服务器端 TCP ESTABELLISHED 状态对应的全连接队列长度。参考
java
// BIO
Socket client = new Socket(hostName, port);
client.setKeepAlive(true);
// NIO
socketChannel.setOption(StandardSocketOptions.SO_KEEPALIVE, true);