设为首页 加入收藏

TOP

聊聊 TCP 中的 KeepAlive 机制(二)
2017-12-19 17:24:58 】 浏览:888
Tags:聊聊 TCP KeepAlive 机制
toi(env)) >= 0)) { setsockopt(s, SOL_TCP, TCP_KEEPCNT, &optval, sizeof(optval)); } #endif #ifdef TCP_KEEPIDLE if((env = getenv("KEEPIDLE")) && ((optval = atoi(env)) >= 0)) { setsockopt(s, SOL_TCP, TCP_KEEPIDLE, &optval, sizeof(optval)); } #endif #ifdef TCP_KEEPINTVL if((env = getenv("KEEPINTVL")) && ((optval = atoi(env)) >= 0)) { setsockopt(s, SOL_TCP, TCP_KEEPINTVL, &optval, sizeof(optval)); } #endif } } return s; }

代码摘取自libkeepalive源码,C语言可以设置更为详细的TCP内核参数

在Nginx中配置

在Nginx中配置TCP的KeepAlive非常简单,在listen指令下配置so_keepalive就可以了,具体配置

so_keepalive=on|off|[keepidle]:[keepintvl]:[keepcnt]

this parameter (1.1.11) configures the “TCP keepalive” behavior for the listening socket. If this parameter is omitted then the operating system’s settings will be in effect for the socket. If it is set to the value “on”, the SO_KEEPALIVE option is turned on for the socket. If it is set to the value “off”, the SO_KEEPALIVE option is turned off for the socket. Some operating systems support setting of TCP keepalive parameters on a per-socket basis using the TCP_KEEPIDLE, TCP_KEEPINTVL, and TCP_KEEPCNT socket options. On such systems (currently, Linux 2.4+, NetBSD 5+, and FreeBSD 9.0-STABLE), they can be configured using the keepidle, keepintvl, and keepcnt parameters. One or two parameters may be omitted, in which case the system default setting for the corresponding socket option will be in effect.

例子

so_keepalive=30m::10
will set the idle timeout (TCP_KEEPIDLE) to 30 minutes,
leave the probe interval (TCP_KEEPINTVL) at its system default,
and set the probes count (TCP_KEEPCNT) to 10 probes.

使用的场景

一般我们使用KeepAlive时会修改空闲时长,避免资源浪费,系统内核会为每一个TCP连接 建立一个保护记录,相对于应用层面效率更高。

常见的几种使用场景:

  1. 检测挂掉的连接(导致连接挂掉的原因很多,如服务停止、网络波动、宕机、应用重启等)
  2. 防止因为网络不活动而断连(使用NAT代理或者防火墙的时候,经常会出现这种问题)
  3. TCP层面的心跳检测

KeepAlive通过定时发送探测包来探测连接的对端是否存活, 但通常也会许多在业务层面处理的,他们之间的特点:

  1. TCP自带的KeepAlive使用简单,发送的数据包相比应用层心跳检测包更小,仅提供检测连接功能
  2. 应用层心跳包不依赖于传输层协议,无论传输层协议是TCP还是UDP都可以用
  3. 应用层心跳包可以定制,可以应对更复杂的情况或传输一些额外信息
  4. KeepAlive仅代表连接保持着,而心跳包往往还代表客户端可正常工作

和Http中Keep-Alive的关系

  1. HTTP协议的Keep-Alive意图在于连接复用,同一个连接上串行方式传递请求-响应数据
  2. TCP的KeepAlive机制意图在于保活、心跳,检测连接错误

参考资料

首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇JVM 堆内存和非堆内存 下一篇Spring 接口支持返回多种格式

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目