关于http:HAProxy Keep-Alive无法正常工作

HAProxy Keep-Alive not working as expected

我对HTTP Keep-Alive的推理正确吗?这是我的假设:

  • 在现代浏览器中,持久连接是默认设置,因此HAProxy不太可能为那些客户端发送Connection:Keep-Alive响应标头。没有看到它并不一定意味着该连接不是持久的。
  • "保持活动"的持续时间较短,例如几百毫秒,在此期间,客户端可以重用与同一服务器的相同连接(用于下载同一页面上的图像,CSS和JavaScript等用途)
  • 通过Cookie或粘贴表可以实现更长的持久性

我问的原因是因为当我设置一个长的keep-alive超时(通过timeout http-keep-alive)时,键入F5会以同样快的速度快速加载另一台后端服务器,在所有这三个服务器之间轮换,而不受keep-alive的影响。我本以为,如果在五秒钟的保持活动超时时间内击中F5,我仍然会获得相同的后端服务器。

我在想这个错误吗?

这是我的HAproxy配置,在其中我将keep-alive超时设置为5秒:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
defaults
  timeout connect 5s
  timeout client 120s
  timeout server 120s
  timeout http-request 5s
  timeout http-keep-alive 5s
  option http-keep-alive

frontend http
  mode http
  bind *:80
  default_backend servers1

backend servers1
  mode http
  balance roundrobin
  server web1 web1:80 check
  server web2 web2:80 check
  server web3 web3:80 check

更新

从客户端的角度来看,使用Wireshark看起来,客户端正在重用与HAProxy前端相同的套接字连接,直到超时为止。因此,保持活动状态似乎在客户端和前端之间起作用。但是,我在网页上添加了一个图像,以查看将由哪个后端服务器提供服务,以及该服务器是否与为HTML提供服务的服务器不同……并且它是不同的。在循环模式下,即使我启用了保持活动状态,两个不同的后端服务器也将内容提供给同一客户端。

在我看来,这一切似乎都使前端和后端之间无法保持活动。如果设置了option http-server-close,这是我期望的行为,但是使用option http-keep-alive时,这不是我期望的,这应该保持与服务器的连接保持打开状态。


  • 您应该确保服务器不会关闭连接。

  • 您应该在HAProxy的默认部分中启用" option preferred-last-server"选项。
  • 您应该重新阅读HAProxy的" option http-keep-alive"文档:http://cbonte.github.io/haproxy-dconv/configuration-1.6.html#option%20http-keep-alive。
    它明确指出:
  • If the client request has to go to another backend or another server due to content switching or the load balancing algorithm, the idle connection will immediately be closed and a new one re-opened. Option"prefer-last-server" is available to try optimize server selection so that if the server currently attached to an idle connection is usable, it will be used.

    (因此,第2点)

    因此,您的观察结果看起来很正常。