聊聊 TCP 中的 KeepAlive 机制

KeepAlive并不是TCP协议规范的一部分,但在几乎所有的TCP/IP协议栈(不管是Linux还是Windows)中,都实现了KeepAlive功能

RFC1122#TCP Keep-Alives

如何设置它?

在设置之前我们先来看看KeepAlive都支持哪些设置项

  1. KeepAlive默认情况下是关闭的,可以被上层应用开启和关闭
  2. tcp_keepalive_time: KeepAlive的空闲时长,或者说每次正常发送心跳的周期,默认值为7200s(2小时)
  3. tcp_keepalive_intvl: KeepAlive探测包的发送间隔,默认值为75s
  4. tcp_keepalive_probes: 在tcp_keepalive_time之后,没有接收到对方确认,继续发送保活探测包次数,默认值为9(次)

我们讲讲在Linux操作系统和使用Java、C语言和Nginx中如何设置

在Linux内核设置

KeepAlive默认不是开启的,如果想使用KeepAlive,需要在你的应用中设置SO_KEEPALIVE才可以生效。

查看当前的配置:

1
2
3
cat /proc/sys/net/ipv4/tcp_keepalive_time
cat /proc/sys/net/ipv4/tcp_keepalive_intvl
cat /proc/sys/net/ipv4/tcp_keepalive_probes

在Linux中我们可以通过修改 /etc/sysctl.conf 的全局配置:

1
2
3
net.ipv4.tcp_keepalive_time=7200
net.ipv4.tcp_keepalive_intvl=75
net.ipv4.tcp_keepalive_probes=9

添加上面的配置后输入 sysctl -p 使其生效,你可以使用 sysctl -a | grep keepalive 命令来查看当前的默认配置

如果应用中已经设置SO_KEEPALIVE,程序不用重启,内核直接生效

使用Netty4设置

这里我们使用常用的Java网络框架Netty来设置,只需要在服务端设置即可:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
EventLoopGroup bossGroup   = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup)
            .channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_BACKLOG, 100)
            .childOption(ChannelOption.SO_KEEPALIVE, true)
            .handler(new LoggingHandler(LogLevel.INFO));
 
    // Start the server.
    ChannelFuture f = b.bind(8088).sync();
    // Wait until the server socket is closed.
    f.channel().closeFuture().sync();
} finally {
    // Shut down all event loops to terminate all threads.
    bossGroup.shutdownGracefully();
    workerGroup.shutdownGracefully();
}

这段代码来自经典的echo服务器,我们在childOption中开启了SO_KEEPALIVE。 Java程序只能做到设置SO_KEEPALIVE选项,其他配置项只能依赖于sysctl配置,系统进行读取。

C语言设置

函数原型:

1
2
3
4
#include <sys/socket.h>
 
int setsockopt(int socket, int level, int option_name,
      const void *option_value, socklen_t option_len);

我们在需要使能Keepalive的socket上面调用setsockopt函数便可以打开该socket上面的keepalive。

  1. 第一个参数是要设置的套接字
  2. 第二个参数是SOL_SOCKET
  3. 第三个参数必须是SO_KEEPALIVE
  4. 第四个参数必须是一个布尔整型值,0表示关闭,1表示打开
  5. 最后一个参数是第四个参数值的大小。

调用例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
int socket(int domain, int type, int protocol)
{
  int (*libc_socket)(int, int, int);
  int s, optval;
  char *env;
 
  *(void **)(&libc_socket) = dlsym(RTLD_NEXT, "socket");
  if(dlerror()) {
    errno = EACCES;
    return -1;
  }
 
  if((s = (*libc_socket)(domain, type, protocol)) != -1) {
    if((domain == PF_INET) && (type == SOCK_STREAM)) {
      if(!(env = getenv("KEEPALIVE")) || strcasecmp(env, "off")) {
        optval = 1;
      } else {
        optval = 0;
      }
      if(!(env = getenv("KEEPALIVE")) || strcasecmp(env, "skip")) {
        setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, &optval, sizeof(optval));
      }
#ifdef TCP_KEEPCNT
      if((env = getenv("KEEPCNT")) && ((optval = atoi(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就可以了,具体配置

1
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.

例子

1
2
3
4
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机制意图在于保活、心跳,检测连接错误

参考资料

http://www.importnew.com/27624.html

posted @ 2018-04-13 17:08  zzfx  阅读(1273)  评论(0编辑  收藏  举报