深入haproxy安装配置与调优详解

发布时间:2020-04-21编辑:脚本学堂
本文介绍下,在linux中,haproxy的安装、配置与调化的详细内容,有需要的朋友参考下吧。
应用举例

WEB 均衡负载 & 虚拟主机
重新打开配置文件 haproxy.cfg,留意最下部分的均衡主机选项
 

复制代码 代码示例:
listen localhost 0.0.0.0:1080 #运行的端口及主机名
mode http
option httpchk GET /index.htm #用于健康检测的后端页面
server s1 127.0.0.1:3121 weight 3 check #后端的主机 IP &权衡
server s2 127.0.0.1:3122 weight 3 check #后端的主机 IP &权衡

在实验中,我们的的后端是 squid 分开了2个端口在同一台服务器上。
以其中一项为例:
 

复制代码 代码示例:
server s1 127.0.0.1:3121 weight 3 check

s1 是可自己定义的服务器别名
127.0.0.1:3121 服务器的IP地址以及端口号
weight 3 所能分配到请求的高低权衡,数字越大分配到的请求数就越高
check 接受 haproxy 的定时检查,以确定后端服务器的健康情况。

如需配置虚拟主机,相当简单,修改 localhost 为虚拟主机的的域名,加到haproxy配置中,再为其分配后端服务器的参数即可。

例:
 

复制代码 代码示例:

listen www.x1.com 0.0.0.0:1080 #运行的端口及主机名
mode http
option httpchk GET /index.htm #用于健康检测的后端页面
server s1 127.0.0.1:3121 weight 3 check #后端的主机 IP &权衡
server s2 127.0.0.1:3122 weight 3 check #后端的主机 IP &权衡

listen www.x2.com 0.0.0.0:1080 #运行的端口及主机名
mode http
option httpchk GET /index.htm #用于健康检测的后端页面
server s1 127.0.0.1:3121 weight 3 check #后端的主机 IP &权衡
server s2 127.0.0.1:3122 weight 3 check #后端的主机 IP &权衡

保存配置后重新加载,即可生效,刷新管理页面也可看到新的虚拟主机。

性能对比
在此,我们用最近最火红的 http 兼前端WEB均衡负载服务器 nginx 与 Haproxy 做个简单的性能对比。
测试环境:

CPU:Xeon2.8G X2
RAM:4G
OS:redhat As5.3 X64

工具:apache ab
参数:ab -i -c 500 -n 100000 (500并发,1W请求)
最终服务端:2个squid 需实现均衡负载

如下:
 

复制代码 代码示例:

####### Nginx + haproxy : (由Nginx通过反向代理发送请求至haproxy, 并由其进行均衡负载)
Concurrency Level: 500
Time taken for tests: 53.758 seconds
Complete requests: 100000
Failed requests: 0
Write errors: 0
Total transferred: 38600386 bytes
HTML transferred: 0 bytes

Requests per second: 1860.19 [#/sec] (mean)
Time per request: 268.790 [ms] (mean)
Time per request: 0.538 [ms] (mean, across all concurrent requests)
Transfer rate: 701.21 [Kbytes/sec] received
####### haproxy : (单独由haproxy进行均衡负载)
Concurrency Level: 500
Time taken for tests: 32.562 seconds
Complete requests: 100000
Failed requests: 0
Write errors: 0
Total transferred: 36606588 bytes
HTML transferred: 0 bytes
Requests per second: 3071.02 [#/sec] (mean)
Time per request: 162.812 [ms] (mean)
Time per request: 0.326 [ms] (mean, across all concurrent requests)
Transfer rate: 1097.85 [Kbytes/sec] received
####### nginx : (单独由nginx进行均衡负载)
Concurrency Level: 500
Time taken for tests: 36.539 seconds
Complete requests: 100000
Failed requests: 0
Write errors: 0
Total transferred: 38600000 bytes
HTML transferred: 0 bytes
Requests per second: 2736.82 [#/sec] (mean)
Time per request: 182.694 [ms] (mean)
Time per request: 0.365 [ms] (mean, across all concurrent requests)
Transfer rate: 1031.65 [Kbytes/sec] received

总结:
Haproxy 单独进行均衡负载的性能最强,超过了Nginx。
然而 Nginx + Haproxy 的搭配性能最弱,应该是跟通过了2层反向代理有关。
所以想用 Haproxy 替代 Nginx 所自带的均衡负载功能将会令性能打折。
即便如此,Haproxy 对均衡负载功能远比 Nginx 成熟,例如session粘贴,cookies 引导等都是 nginx 所没有的。
在实际的生产环境中,大家可以根据需要而选择搭配,无论haproxy,还是nginx都是很优秀的软件,呵呵。