TCP keepalives
TCP keepalives可以在客户端或服务端的应用层开启,开启后进程会定时发送报文来检测对端是否崩溃,崩溃则关闭连接。
使用上keep alive的一个场景如下:A和B通过三次握手建立连接,然后拔掉B服务器的电源,这时B没有机会去发送连接关闭的请求,然后B服务器重启,这时对于A来说连接是健康的,但B不知道这个连接,当A发送请求时会失败
该功能在应用层开启,默认配置在操作系统层,linux的示例如下
配置含义:当连接保持tcp_keepalive_time的idle后会发起探活请求,如果没收到ACK会在tcp_keepalive_intvl*n(n为第n次重试)后再次发送,一共会尝试tcp_keepalive_probes次,如果最后仍没收到ACK则会丢弃该TCP连接。
net.ipv4.tcp_keepalive_time = 7200
net.ipv4.tcp_keepalive_intvl = 75
net.ipv4.tcp_keepalive_probes = 9
优点
- 尽快释放连接资源
- 避免使用失效的连接。这种情况通常请求不会被主动拒绝,而是简单地超时,可能会在几秒钟甚至几分钟之后。
缺点
- 在出现短暂的差错时,可能使好连接释放
- 耗费不必要的带宽
ElasticSearch keepalive
默认开启应用层自己实现的keepalive,但官方文档推荐使用TCP keepalives
应用层自己实现的keepalive
具体代码在TransportKeepAlive类。当ES节点(服务端)向另一个ES节点(客户端)建立transport connection时会同时发起KeepAlive调度,每5s向连接对端发送探活请求,失败则关闭连接。调度间隔可以通过transport.ping_schedule参数配置
开启ES keepalives
使用配置network.tcp.keep_alive。默认开启。但调度间隔取决于操作系统配置,默认为2h
Rest Client keepalive
Rest Client通过配置httpasyncclient来配置TCP keepalive,默认关闭,但官方建议开启。https://github.com/elastic/elasticsearch/issues/65213
final RestClientBuilder restClientBuilder = RestClient.builder(/* fill in arguments here */);
// optionally perform some other configuration of restClientBuilder here if needed
restClientBuilder.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder
/* optionally perform some other configuration of httpClientBuilder here if needed */
.setDefaultIOReactorConfig(IOReactorConfig.custom()
/* optionally perform some other configuration of IOReactorConfig here if needed */
.setSoKeepAlive(true)
.build()));
final RestHighLevelClient restHighLevelClient = new RestHighLevelClient(restClientBuilder);
mac配置参数方法
# 查看配置,单位 毫秒
$ sysctl net.inet.tcp | grep -E "keepidle|keepintvl|keepcnt"
net.inet.tcp.keepidle: 7200000
net.inet.tcp.keepintvl: 75000
net.inet.tcp.keepcnt: 8
# 修改配置
sudo sysctl -w net.inet.tcp.keepidle=180000 net.inet.tcp.keepcnt=3 net.inet.tcp.keepintvl=10000
相关文档
https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html
https://www.bookstack.cn/read/elasticsearch-7.9-en/321fbc00b383ef77.md
https://www.bookstack.cn/read/elasticsearch-7.9-en/9a9abf9168effbcb.md
https://www.cnblogs.com/anruy/p/4895942.html