HAProxy:负载均衡的卓越之选

        在现代云计算和微服务架构中,负载均衡器是确保应用高可用性和扩展性的关键组件。HAProxy,作为一款广受好评的开源负载均衡解决方案,提供了一系列的功能和优化,使其成为企业和开发者的首选。以下是对HAProxy特性的综合介绍,按照其功能和优势进行分类。

一、HAProxy概述

1.1 定义与应用场景

        HAProxy是一款开源软件,由Willy Tarreau开发,专为处理高并发网络流量而设计。它不仅支持HTTP和TCP协议的负载均衡,还具备SSL卸载、连接管理、会话保持等高级功能,适用于从小型网站到大型企业级应用的各种场景。
 

二、核心特性


        HAProxy的核心特性是其成为顶级负载均衡解决方案的关键因素。以下是对HAProxy核心特性的详细阐述:


2.1 高性能设计

HAProxy的高性能设计基于以下几个关键点:
异步事件驱动架构:此架构允许HAProxy在不牺牲性能的情况下处理大量并发连接。
优化的网络栈:HAProxy针对网络操作进行了优化,减少了系统调用和上下文切换的开销。
多核支持:能够充分利用多核处理器的优势,提高并行处理能力。

2.2 高可靠性保障

HAProxy的高可靠性体现在:
故障转移:在后端服务器发生故障时,HAProxy能够自动将流量切换到健康的服务器。
健康检查:定期对后端服务器进行健康检查,确保流量只发送到可用的服务。
持久连接:支持HTTP持久连接,减少了连接建立和关闭的开销。

2.3 智能负载均衡

HAProxy提供了多种负载均衡策略,以适应不同的应用场景:
轮询(Round Robin):简单均匀地分配请求到各个服务器。
最少连接(Least Connections):优先将请求分配给连接数最少的服务器。
源地址哈希(Source IP Hash):基于客户端IP地址进行哈希,确保来自同一客户端的请求总是路由到同一服务器。

2.4 SSL处理能力

HAProxy的SSL处理能力包括:
SSL终结:在HAProxy层面处理SSL握手,减轻后端服务器的负担。
SSL加速:使用专用硬件进行SSL加密和解密,提高性能。
SSL/TLS协议支持:支持最新的SSL/TLS协议和密码套件。

2.5 会话保持策略

HAProxy支持多种会话保持策略,以满足不同的业务需求:
基于cookie的会话保持:通过在客户端设置cookie来保持会话状态。
基于IP的会话保持:通过客户端IP地址来保持会话,适用于无状态的客户端。

2.6 定制化配置

HAProxy的定制化配置允许用户:
自定义负载均衡算法:根据业务需求定制负载均衡逻辑。
配置扩展:通过自定义脚本或命令扩展HAProxy的功能。

三、实践

3.1 实验环境配置

三台虚拟机RHEL9.4

haproxy:网卡eth0、IP为172.25.254.100

webserver1:网卡eth0、IP为172.25.254.10

webserver2:网卡eth0、IP为172.25.254.20

1. 关闭三台主机的防火墙

systemctl stop firewalld

2. 在两台webserver上分别安装nginx

#webserver1
[root@webserver1 ~]# dnf install nginx -y
[root@webserver1 ~]# echo webserver1:172.25.254.10 > /usr/share/nginx/html/index.html
[root@webserver1 ~]# systemctl enable --now nginx.service 
Created symlink /etc/systemd/system/multi-user.target.wants/nginx.service → /usr/lib/systemd/system/nginx.service.

#webserver2
[root@webserver2 ~]# dnf install nginx -y
[root@webserver2 ~]# echo webserver2:172.25.254.20 > /usr/share/nginx/html/index.html
[root@webserver2 ~]# systemctl enable --now nginx.service 
Created symlink /etc/systemd/system/multi-user.target.wants/nginx.service → /usr/lib/systemd/system/nginx.service.

# 客户端访问
[root@haproxy ~]# curl 172.25.254.10
webserver1:172.25.254.10
[root@haproxy ~]# curl 172.25.254.20
webserver2:172.25.254.20

3. haproxy的基本部署方法以及负载均衡的实现

# 在haproxy主机上安装haproxy
[root@haproxy ~]# dnf install haproxy -y

# 更改配置文件设定
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
# 将以下内容写入配置文件中
frontend webcluster
    bind *:80
    mode http
    use_backend webcluster-host

backend webcluster-host
    balance roundrobin
    server  web1 172.25.254.10:80
    server  web2 172.25.254.20:80

#重启服务
[root@haproxy ~]# systemctl restart haproxy.service
[root@haproxy ~]# systemctl enable haproxy.service 

#本机访问
[C:\~]$ curl 172.25.254.100
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    25  100    25    0     0   9211      0 --:--:-- --:--:-- --:--:-- 12500
webserver1:172.25.254.10

[C:\~]$ curl 172.25.254.100
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    25  100    25    0     0  10660      0 --:--:-- --:--:-- --:--:-- 12500
webserver2:172.25.254.20


4. haproxy的全局配置参数以及日志分离

#查看haproxy的默认进程
[root@haproxy ~]# pstree -p | grep haproxy
           |-haproxy(32904)---haproxy(32906)---{haproxy}(32907)
# 将`nbproc 2`添加到配置文件的global中,代表启用多线程
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg 
nbproc 2 # 启用多进程

#重启服务查看
[root@haproxy ~]# systemctl restart haproxy.service 
[root@haproxy ~]# pstree -p | grep haproxy
           |-haproxy(32924)-+-haproxy(32926)
           |                `-haproxy(32927)

	cpu-map 1 0 
    cpu-map 2 1

#查看修改后的进程
[root@haproxy ~]# systemctl restart haproxy.service 
[root@haproxy ~]# pstree -p | grep haproxy
           |-haproxy(32944)-+-haproxy(32945)
           |                `-haproxy(32946)

查看子进程

[root@haproxy ~]# cat /proc/32945/status | grep -i thread
Threads:	1

同时设定多线程和多进程,会产生互斥,将其注释后重启服务查看

# turn on stats unix socket
    stats socket /var/lib/haproxy/stats

# utilize system-wide crypto-policies
    ssl-default-bind-ciphers PROFILE=SYSTEM
    ssl-default-server-ciphers PROFILE=SYSTEM
    #nbproc 2
    #cpu-map 1 0
    #cpu-map 2 1
    nbthread 2
[root@haproxy ~]# systemctl restart haproxy.service 
[root@haproxy ~]# pstree -p | grep haproxy
           |-haproxy(33009)---haproxy(33011)---{haproxy}(33012)
[root@haproxy ~]# cat /proc/33011/status | grep -i thread
Threads:	2

5. 自定义haproxy日志

[root@haproxy ~]# vim /etc/rsyslog.conf
···
# 将这两行取消注释,同时打开udp端口

module(load="imudp") # needs to be done just once
input(type="imudp" port="514")



[root@haproxy ~]# ll /var/log/haproxy.log
[root@haproxy ~]# systemctl restart rsyslog.service


5. haproxy的热更新方法

在haproxy上安装socat

dnf install socat -y

#修改配置文件
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
stats socket /var/lib/haproxy/stats mode 600 level admin

#查看haproxy状态
[root@haproxy ~]# echo "show info" | socat stdio /var/lib/haproxy/stats
Name: HAProxy
Version: 2.4.22-f8e3218
Release_date: 2023/02/14
Nbthread: 1
Nbproc: 1
Process_num: 1
Pid: 3352
Uptime: 0d 0h03m43s
Uptime_sec: 223
Memmax_MB: 0
PoolAlloc_MB: 0

#查看集群状态
[root@haproxy ~]# echo "show servers state" | socat stdio /var/lib/haproxy/stats
1
# be_id be_name srv_id srv_name srv_addr srv_op_state srv_admin_state srv_uweight
srv_iweight srv_time_since_last_change srv_check_status srv_check_result
srv_check_health srv_check_state srv_agent_state bk_f_forced_id srv_f_forced_id
srv_fqdn srv_port srvrecord srv_use_ssl srv_check_port srv_check_addr
srv_agent_addr srv_agent_port
2 webcluster 1 web1 172.25.254.20 2 0 2 2 188 6 3 7 6 0 0 0 - 80 - 0 0 - - 0
2 webcluster 2 web2 172.25.254.30 2 0 1 1 188 6 3 7 6 0 0 0 - 80 - 0 0 - - 0
4 static 1 static 127.0.0.1 0 0 1 1 187 8 2 0 6 0 0 0 - 4331 - 0 0 - - 0
5 app 1 app1 127.0.0.1 0 0 1 1 187 8 2 0 6 0 0 0 - 5001 - 0 0 - - 0
5 app 2 app2 127.0.0.1 0 0 1 1 187 8 2 0 6 0 0 0 - 5002 - 0 0 - - 0
5 app 3 app3 127.0.0.1 0 0 1 1 186 8 2 0 6 0 0 0 - 5003 - 0 0 - - 0
5 app 4 app4 127.0.0.1 0 0 1 1 186 8 2 0 6 0 0 0 - 5004 - 0 0 - - 0

#查看集群权重
[root@haproxy ~]# echo get weight webcluster/web1 | socat stdio
/var/lib/haproxy/stats
2 (initial 2)
[root@haproxy ~]# echo get weight webcluster/web2 | socat stdio
/var/lib/haproxy/stats
1 (initial 1)

#设置权重
[root@haproxy ~]# echo "set weight webcluster/web1 1 " | socat stdio
/var/lib/haproxy/stats
[root@haproxy ~]# echo "set weight webcluster/web1 2 " | socat stdio
/var/lib/haproxy/stats

#下线后端服务器
[root@haproxy ~]# echo "disable server webcluster/web1 " | socat stdio
/var/lib/haproxy/stats

#上线后端服务器
[root@haproxy ~]# echo "enable server webcluster/web1 " | socat stdio
/var/lib/haproxy/stats



[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg

stats socket /var/lib/haproxy/stats1 mode 600 level admin process 1
stats socket /var/lib/haproxy/stats2 mode 600 level admin process 2
nbproc 2
cpu-map 1 0
cpu-map 2 1

#每个进程会有单独的sock文件来进行单独管理
[root@haproxy ~]# ll /var/lib/haproxy/
总用量 0
srw------- 1 root root 0 8月 11 13:43 stats
srw------- 1 root root 0 8月 11 13:46 stats1
srw------- 1 root root 0 8月 11 13:46 stats2


6. haproxy算法

静态算法

1. static-rr:基于权重的轮询调度,不支持运行时动态调整权重,仅支持0和1的权重设置,且不关心后端服务器的负载情况。

[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg 

listen webcluster
   bind *:80
   mode http
   #balance first
   balance static-rr
   server  web1 172.25.254.10:80 check inter 2 fall 3 rise 5 weight 2
   server  web2 172.25.254.20:80 check inter 2 fall 3 rise 5 weight 1
   
[root@haproxy ~]# systemctl restart haproxy.service

#测试
[root@test ~]# for i in {1..10}; do curl 172.25.254.100; done
webserver2:172.25.254.20
webserver1:172.25.254.10
webserver2:172.25.254.20
webserver1:172.25.254.10
webserver2:172.25.254.20
webserver1:172.25.254.10
webserver2:172.25.254.20
webserver1:172.25.254.10
webserver2:172.25.254.20
webserver1:172.25.254.10


2. first:根据服务器列表顺序进行调度,当第一台服务器达到连接上限时,请求才会分配给下一台服务器,忽略权重设置。
动态算法
1. roundrobin:最常用的基于权重的轮询动态调度算法,支持运行时权重调整和慢启动,每个后端最多支持4095个real server。

[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg 

listen webcluster
   bind *:80
   mode http
   balance roundrobin
   server  web1 172.25.254.10:80 check inter 2 fall 3 rise 5 weight 2
   server  web2 172.25.254.20:80 check inter 2 fall 3 rise 5 weight 1
   

[root@haproxy ~]# systemctl restart haproxy.service


2. leastconn:加权最少连接数动态调度算法,优先将请求分配给当前连接数最少的服务器,支持权重调整和慢启动,适合长连接场景,如数据库连接。
3. random:基于随机数的调度算法,支持权重调整,权重较大的服务器有更高概率接收新请求。
其他算法
1. source:基于客户端源地址hash的调度,后续同一个源地址的请求会被转发至同一个后端服务器。

[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg 

listen webcluster
   bind *:80
   mode http
   balance source
   server  web1 172.25.254.10:80 check inter 2 fall 3 rise 5 weight 2
   server  web2 172.25.254.20:80 check inter 2 fall 3 rise 5 weight 1
   

[root@haproxy ~]# systemctl restart haproxy.service

[root@test ~]# for i in {1..10}; do curl 172.25.254.100; done
webserver2:172.25.254.20
webserver2:172.25.254.20
webserver2:172.25.254.20
webserver2:172.25.254.20
webserver2:172.25.254.20
webserver2:172.25.254.20
webserver2:172.25.254.20
webserver2:172.25.254.20
webserver2:172.25.254.20
webserver2:172.25.254.20


2. map-base:取模法,对源地址进行hash计算,再根据服务器总权重取模决定请求转发。
3. 一致性hash:在哈希环上进行调度,当服务器数量变化时,只影响局部请求的分配,支持动态权重调整和慢启动。
4. uri:基于用户请求的URI进行hash,适用于缓存服务器场景。
5. url_param:基于URL参数进行hash,可以实现session保持。
6. hdr:基于HTTP请求头部进行hash。
算法使用场景
first:使用较少,适用于节约成本的场景。
static-rr 和 roundrobin:适用于需要session共享的web集群。
random:适用于需要session共享且服务器数量较多的场景。
leastconn:适用于数据库等长连接场景。
source:适用于基于客户端公网IP的会话保持。
uri、url_param 和 hdr:适用于特定的应用层负载均衡需求。
 

3.2 高级功能及配置

1. haproxy的状态页面监控

[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg 


listen stats
    mode http
    bind *:4567
    stats enable
    stats refresh 1
    stats uri /status
    stats auth www:www

[root@haproxy ~]# systemctl restart haproxy.service 

浏览器测试

2. cookie的会话保持

[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg

listen webcluster
   bind *:80
   mode http
   balance roundrobin
   cookie WEBCOOKIE insert nocache indirect
   server  web1 172.25.254.10:80 cookie web1 check inter 2 fall 3 rise 5 weight 1
   server  web2 172.25.254.20:80 cookie web2 check inter 2 fall 3 rise 5 weight 1


[root@haproxy ~]# systemctl restart haproxy.service

3. haproxy-ip透传

# haproxy配置
# 在由haproxy发往后端主机的请求报文中添加“X-Forwarded-For"首部,其值为前端客户端的地址;用于向后端主机发送真实的客户端IP
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg 

listen webcluster
   bind *:80
   mode http
   #balance first
   #balance static-rr
   balance roundrobin
   #balance leastconn
   #balance source
   #balance uri
   #balance url_param name,userid
   #balance hdr(User-Agent)
   #hash-type consistent
  # redirect prefix http://www.baidu.com/
   #cookie WEBCOOKIE insert nocache indirect
   server  web1 172.25.254.10:80 check inter 2 fall 3 rise 5 weight 1
   server  web2 172.25.254.20:80 send-proxy check inter 2 fall 3 rise 5 weight 1
#   server web_sorry 172.25.254.100:8080 backup


[root@haproxy ~]# systemctl restart haproxy.service

[root@webserver1 ~]# systemctl disable nginx.service 
[root@webserver1 ~]# systemctl stop nginx.service 
[root@webserver1 ~]# dnf install httpd -y
[root@webserver1 ~]# echo web1 - 172.25.254.10 > /var/www/html/index.html
[root@webserver1 ~]# systemctl start httpd
[root@webserver1 ~]# vi /etc/httpd/conf/httpd.conf 
# 配置web服务器,记录负载均衡透传的客户端IP地址

	
	LogFormat  "%{X-Forwarded-For}i %h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
    LogFormat "%h %l %u %t \"%r\" %>s %b" common

    <IfModule logio_module>
      # You need to enable mod_logio.c to use %I and %O
      LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
    </IfModule>



[root@webserver1 ~]# systemctl restart httpd

[C:\~]$ curl 172.25.254.100
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    25  100    25    0     0  10794      0 --:--:-- --:--:-- --:--:-- 12500
webserver2:172.25.254.20

[C:\~]$ curl 172.25.254.100
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    21  100    21    0     0   6231      0 --:--:-- --:--:-- --:--:--  7000
web1 - 172.25.254.10

[C:\~]$ curl 172.25.254.100
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    21  100    21    0     0   7996      0 --:--:-- --:--:-- --:--:-- 10500
web1 - 172.25.254.10

[root@webserver1 ~]# tail /etc/httpd/logs/access_log 
172.25.254.1 172.25.254.100 - - [10/Aug/2024:22:39:31 +0800] "GET / HTTP/1.1" 200 27 "-" "curl/8.7.1"
172.25.254.1 172.25.254.100 - - [10/Aug/2024:22:41:33 +0800] "GET / HTTP/1.1" 200 27 "-" "curl/8.7.1"
172.25.254.1 172.25.254.100 - - [10/Aug/2024:22:41:34 +0800] "GET / HTTP/1.1" 200 27 "-" "curl/8.7.1"


4. haproxy的访问控制列表

frontend webcluster
     bind *:80
     mode http
     acl test hdr_dom(host) -i www.abc.org
     use_backend webcluster-host if test
     default_backend default-host

backend webcluster-host
     mode http
     server web1 172.25.254.10:80 check inter 2 fall 2 rise 5

backend default-host
     mode http
     server web2 172.25.254.20:80 check inter 2 fall 2 rise 5
[C:\~]$ curl 172.25.254.100
[C:\~]$ curl www.abc.org

重定向错误页面

[root@webserver1 ~]# systemctl stop httpd.service

[root@webserver2 ~]# systemctl stop nginx.service

[root@haproxy ~]# mkdir /etc/haproxy/errorpage -p
[root@haproxy ~]# vim /etc/haproxy/errorpage/503.http 
HTTP/1.0 503 Service Unavailable
Cache-Control: no-cache
Connection: close
Content-Type: text/html;charset=UTF-8

<html><body><h1>什么动物生气最安静</h1>
大猩猩!!
</body></html>


[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg 
defaults
    mode                    http
    log                     global
    option                  httplog
    option                  dontlognull
    option http-server-close
    option forwardfor       except 127.0.0.0/8
    option                  redispatch
    retries                 3
    timeout http-request    10s
    timeout queue           1m
    timeout connect         10s
    timeout client          1m
    timeout server          1m
    timeout http-keep-alive 10s
    timeout check           10s
    maxconn                 3000
    errorfile 503 /etc/haproxy/errorpage/503.http
    
[root@haproxy ~]# systemctl restart haproxy.service
    

5. haproxy的基于https的加密访问

[root@haproxy ~]# mkdir -p /etc/haproxy/certs
[root@haproxy ~]# openssl req -newkey rsa:2048 -nodes -sha256 -keyout /etc/haproxy/certs/wcm.com.key -x509 -days 365 -out /etc/haproxy/certs/wcm.com.crt
.+..........+...........+..........+.....+...+.......+...+...++++++++++++++++++++++++++++++++++++++++++++++++++++++++*..+..+...+.........+....+......+.....+....+..+...+......+...+..........+......+............+.....+.......+.....+.+......+...+...+........+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:CN
State or Province Name (full name) []:ShanXi
Locality Name (eg, city) [Default City]:XiAn
Organization Name (eg, company) [Default Company Ltd]:wcm
Organizational Unit Name (eg, section) []:web
Common Name (eg, your name or your server's hostname) []:www.wcm.com
Email Address []:admin@wcm.com

[root@haproxy ~]# ls /etc/haproxy/certs/
wcm.com.crt  wcm.com.key

[root@haproxy ~]# cat /etc/haproxy/certs/wcm.com.key /etc/haproxy/certs/wcm.com.crt > /etc/haproxy/certs/wcm.pem
[root@haproxy ~]# cat /etc/haproxy/certs/wcm.pem
-----BEGIN PRIVATE KEY-----
MIIEvQIB


#此处省略
-----END CERTIFICATE-----


[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
listen web-https
   bind *:443 ssl crt /etc/haproxy/certs/wcm.pem
   mode http
   balance roundrobin
   server web1 172.25.254.10:443 check inter 2 fall 2 rise 5
   server web2 172.25.254.20:443 check inter 2 fall 2 rise 5

[root@haproxy ~]# systemctl restart haproxy.service 

  • 15
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值