我关于 HTTP Keep-Alive 的推理正确吗?以下是我的假设:
- 在现代浏览器中,持久连接是默认设置,因此 HAProxy 不太可能为这些客户端发送“Connection: Keep-Alive”响应 header 。 没有看到它并不一定意味着连接不是持久的。
- Keep-Alive 的持续时间很短,例如几百毫秒,在此期间客户端可以重复使用与同一服务器的相同连接(用于下载服务器上的图像、CSS 和 JavaScript 等用途)同一页)
- 可以通过 cookies 或粘表来实现更长的持久性
我问的原因是因为当我设置一个较长的保持事件超时(通过timeout http-keep-alive
)时,键入 F5 会快速加载不同的后端服务器,并以同样的速度轮流遍历所有后端服务器三个没有任何保活的影响。我本以为如果我在五秒的保持事件超时期间按 F5,我仍然会得到相同的后端服务器。
我的想法是错误的吗?
这是我的 HAproxy 配置,我将保持事件超时设置为 5 秒:
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 点)
所以你的观察结果看起来很正常。
关于http - HAProxy Keep-Alive 未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35162527/