負載均衡:提升業務性能的關鍵技術

.負載均衡(3.6 )

1.1.什么是負載均衡:

????????負載均衡:Load Balance,簡稱LB,是一種服務或基于硬件設備等實現的高可用反向代理技術,負載均 衡將特定的業務(web服務、網絡流量等)分擔給指定的一個或多個后端特定的服務器或設備,從而提高了 公司業務的并發處理能力、保證了業務的高可用性、方便了業務后期的水平動態擴展。

????????阿里云SLB介紹 :https://yq.aliyun.com/articles/1803

1.2.為什么用負載均衡:

????????Web服務器的動態水平擴展-->對用戶無感知

????????增加業務并發訪問及處理能力-->解決單服務器瓶頸問題

????????節約公網IP地址-->降低IT支出成本

????????隱藏內部服務器IP-->提高內部服務器安全性

????????配置簡單-->固定格式的配置文件

????????功能豐富-->支持四層和七層,支持動態下線主機

????????性能較強-->并發數萬甚至數十萬

1.3.負載均衡類型

1.3.1硬件:

F5????????????????????????美國F5網絡公司 https://f5.com/zh

Netscaler? ? ? ? ? ? ?美國思杰公司 https://www.citrix.com.cn/products/citrix-adc/

Array? ? ? ? ? ? ? ? ? ?華耀 https://www.arraynetworks.com.cn/

AD-1000? ? ? ? ? ? ? 深信服 http://www.sangfor.com.cn/

1.3.2.四層負載均衡:

1.通過ip+port決定負載均衡的去向。

2.對流量請求進行NAT處理,轉發至后臺服務器。

3.記錄tcpudp流量分別是由哪臺服務器處理,后續該請求連接的流量都通過該服務器處理。

4.支持四層的軟件

lvs:重量級四層負載均衡器。

Nginx:輕量級四層負載均衡器,可緩存。(nginx四層是通過upstream模塊)

Haproxy:模擬四層轉發。

1.3.3.七層負載均衡:

1.通過虛擬ur|或主機ip進行流量識別,根據應用層信息進行解析,決定是否需要進行負載均衡。

2.代理后臺服務器與客戶端建立連接,如nginx可代理前后端,與前端客戶端tcp連接,與后端服務器建立 tcp連接,

3.支持7層代理的軟件:

????????Nginx:基于http協議(nginx七層是通過proxy_pass)

????????Haproxy:七層代理,會話保持、標記、路徑轉移等。

1.3.4 四層和七層的區別:

????????所謂的四到七層負載均衡,就是在對后臺的服務器進行負載均衡時,依據四層的信息或七層的信息來決定怎么樣轉發流量。

????????四層的負載均衡,就是通過發布三層的IP地址(VIP),然后加四層的端口號,來決定哪些流量需要做負 載均衡,對需要處理的流量進行NAT處理,轉發至后臺服務器,并記錄下這個TCP或者UDP的流量是由哪 臺服務器處理的,后續這個連接的所有流量都同樣轉發到同一臺服務器處理

七層的負載均衡,就是在四層的基礎上(沒有四層是絕對不可能有七層的),再考慮應用層的特征,比 如同一個Web服務器的負載均衡,除了根據VIP80端口辨別是否需要處理的流量,還可根據七層的 URL、瀏覽器類別、語言來決定是否要進行負載均衡。

1.分層位置:四層負載均衡在傳輸層及以下,七層負載均衡在應用層及以下

2.性能 :四層負載均衡架構無需解析報文消息內容,在網絡吞吐量與處理能力上較高:七層可支持解析應用 層報文消息內容,識別URLCookieHTTP header等信息。、

3.原理 :四層負載均衡是基于ip+port;七層是基于虛擬的URL或主機IP等。

4.功能類比:四層負載均衡類似于路由器;七層類似于代理服務器。

5.安全性:四層負載均衡無法識別DDoS攻擊;七層可防御SYN Cookie/Flood攻擊

.haproxy簡介

HAProxy是法國開發者 威利塔羅(Willy Tarreau) 2000年使用C語言開發的一個開源軟件

是一款具備高并發(萬級以上)、高性能的TCPHTTP負載均衡器 支持基于cookie的持久性,自動故障切換,支持正則表達式及web狀態統計。

企業版網站:https://www.haproxy.com

社區版網站:http://www.haproxy.org

githubhttps://github.com/haprox

企業版本和社區版功能對比

.haproxy的安裝和服務信息

3.1.實驗環境:
功能
IP
clinet
eth0172.,25.254.111
haproxy
eth0172.25.254.50
RS1
eth0:172.25.254.10
RS2
eth0:172.25.254.20
3.2.軟件安裝:
#軟件包下載地址
https://github.com/haproxy/wiki/wiki/Packages
#安裝軟件包:
[haproxy ~]# dnf install haproxy -y
#查看版本
[root@haproxy ~]# haproxy -v
HAProxy version 2.4.22-f8e3218 2023/02/14 - https://haproxy.org/
Status: long-term supported branch - will stop receiving fixes around Q2 2026.
Known bugs: http://www.haproxy.org/bugs/bugs-2.4.22.html
Running on: Linux 5.14.0-427.13.1.el9_4.x86_64 #1 SMP PREEMPT_DYNAMIC Wed Apr 10
10:29:16 EDT 2024 x86_64#haproxy軟件基本信息
軟件安裝包: haproxy-2.4.22-3.el9_3.x86_64.rpm
啟動文件: /lib/systemd/system/haproxy.service
主配置目錄: /etc/haproxy/
主配置文件: /etc/haproxy/haproxy.cfg
子配置目錄: /etc/haproxy/conf.d
3.3.haproxy的基本配置信息:

?官方文檔:http://cbonte.github.io/haproxy-dconv/

?HAProxy 的配置文件haproxy.cfg由兩大部分組成,分別是:

?global:全局配置段

? ? ? ? 進程及安全配置相關的參數

? ? ? ? 性能調整相關參數

????????Debug參數

?proxies:代理配置段

????????defaults:為frontend, backend, listen提供默認配置

????????frontend:前端,相當于nginx中的server {}

????????backend:后端,相當于nginx中的upstream {}

????????listen:同時擁有前端和后端配置,配置簡單,生產推薦使用

3.3.1.2 多進程和線程:

多進程和socket文件配置如下:

haproxy ~]# vim /etc/haproxy/haproxy.cfg
...上面內容省略...
global
log 127.0.0.1 local2
chroot /var/lib/haproxy
pidfile /var/run/haproxy.pid
maxconn 100000
user haproxy
group haproxy
daemon
# turn on stats unix socket
stats socket /var/lib/haproxy/haproxy.sock1 mode 600 level admin process 1 #
啟用多個sock文件
stats socket /var/lib/haproxy/haproxy.sock2 mode 600 level admin process 2
nbproc 2 #啟用多進程
cpu-map 1 0 #進程和cpu核心綁定防止cpu抖動從而減少系統資源消耗
cpu-map 2 1 #2 表示第二個進程,1表示第二個cpu核心
...下面內容省略 ...
查看多進程信息
haproxy haproxy]# pstree -p | grep haproxy
|-haproxy(4816)-+-haproxy(4820)
| `-haproxy(4821)
啟用多線程
[haproxy ~]# vim /etc/haproxy/haproxy.cfg
...上面內容省略...
log 127.0.0.1 local2
chroot /var/lib/haproxy
pidfile /var/run/haproxy.pid
maxconn 100000
user haproxy
group haproxy
daemon
# turn on stats unix socket
stats socket /var/lib/haproxy/haproxy.sock1 mode 600 level admin process 1 #
啟用多個sock文件
stats socket /var/lib/haproxy/haproxy.sock2 mode 600 level admin process 2
#nbproc 2
#cpu-map 1 0
#cpu-map 2 1
nbthread 2 #啟用多線程
...下面內容省略...
多線程對比
未開啟多線程
haproxy ~]# cat /proc/xxxx(haproxy子進程id)/status
...上面內容省略...
Threads: 1
...下面內容省略...
開啟后
haproxy ~]# cat /proc/xxxx(haproxy子進程id)/status
...上面內容省略...
Threads: 2
...下面內容省略...
3.3.2 proxies配置:
3.3.2.1.proxies參數說明proxies:

3.3.2.2 Proxies配置-defaults:

defaults
mode http     #HAProxy實例使用的連接協議
log global     #指定日志地址和記錄日志條目的
syslog/rsyslog 日志設備#此處的 global表示使用 global配置段中設定的log值。
option httplog     #日志記錄選項,httplog表示記錄與 HTTP會話相關的各種屬性值
#包括 HTTP請求、會話狀態、連接數、源地址以及連接時間等
option dontlognull  #dontlognull表示不記錄空會話連接日志
option http-server-close #等待客戶端完整HTTP請求的時間,此處為等待10s。
option forwardfor except 127.0.0.0/8     #透傳客戶端真實IP至后端web服務器#在apache配置文件中加入:<br>%{X-Forwarded-For}i#后在webserver中看日志即可看到地址透傳信息
option redispatch         #當server Id對應的服務器掛掉后,強制定向到其他健康的服務器,重新派發
option http-keep-alive         #開啟與客戶端的會話保持
retries                     #連接后端服務器失敗次數timeout http-request 10s     #等待客戶端請求完全被接收和處理的最長時
間
timeout queue 1m         #設置刪除連接和客戶端收到503或服務不可用等提示信息前的等待時間
timeout connect 120s     #設置等待服務器連接成功的時間
timeout client 600s     #設置允許客戶端處于非活動狀態,即既不發送數據也不接收數據的時間
timeout server 600s     #設置服務器超時時間,即允許服務器處于既不接收也不發送數據的非活動時間
timeout http-keep-alive 60s #session 會話保持超時時間,此時間段內會轉發到相同的后端服務器
timeout check 10s     #指定后端服務器健康檢查的超時時間
maxconn 3000
default-server inter 1000 weight 3

3.3.2.3 Proxies配置-frontend:

frontend 配置參數:

bind:指定HAProxy的監聽地址,可以是IPV4或IPV6,可以同時監聽多個IP或端口,可同時用于listen字段中#格式:
bind [<address>]:<port_range> [, ...] [param*]
#注意:如果需要綁定在非本機的IP,需要開啟內核參數:net.ipv4.ip_nonlocal_bind=1
backlog <backlog> #針對所有server配置,當前端服務器的連接數達到上限后的后援隊列長度,注意:不支持backend

frontend 配置示例:

haproxy ~]# vim /etc/haproxy/haproxy.cfg
...上面內容省略...
frontend lee-webserver-80
bind 172.25.254.100:80
mode http
use_backend lee-webserver-80-RS #調用backend的名稱
...下面內容省略...

3.3.2.4 Proxies配置-backend:

????????定義一組后端服務器,backend服務器將被frontend進行調用。

????????注意: backend 的名稱必須唯一,并且必須在listenfrontend中事先定義才可以使用,否則服務無法 啟動

mode http|tcp #指定負載協議類型,和對應的frontend必須一致
option #配置選項
server #定義后端real server,必須指定IP和端口
注意:option后面加 httpchksmtpchk,mysql-check,pgsql-checkssl-hello-chk方法,可用于實現更 多應用層檢測功能。

server 配置:

#針對一個server配置
check     #對指定real進行健康狀態檢查,如果不加此設置,默認不開啟檢查,只有check后面沒
有其它配置也可以啟用檢查功能#默認對相應的后端服務器IP和端口,利用TCP連接進行周期性健康性檢查,注意必須指定端口才能實現健康性檢查
addr <IP>     #可指定的健康狀態監測IP,可以是專門的數據網段,減少業務網絡的流量
port <num>     #指定的健康狀態監測端口
inter <num>     #健康狀態檢查間隔時間,默認2000 ms
fall <num>     #后端服務器從線上轉為線下的檢查的連續失效次數,默認為3
rise <num>     #后端服務器從下線恢復上線的檢查的連續有效次數,默認為2
weight <weight>     #默認為1,最大值為256,0(狀態為藍色)表示不參與負載均衡,但仍接受持久連接backup #將后端服務器標記為備份狀態,只在所有非備份主機down機時提供服務,類似Sorry
Server
disabled     #將后端服務器標記為不可用狀態,即維護狀態,除了持久模式#將不再接受連接,狀態為深黃色,優雅下線,不再接受新用戶的請求
redirect prefix http://www.baidu.com/     #將請求臨時(302)重定向至其它URL,只適用于http模式
maxconn <maxconn>     #當前后端server的最大并發連接數
代碼示例:
haproxy ~]# vim /etc/haproxy/haproxy.cfg
...上面內容省略...
backend lee-webserver-80-RS
mode http
server web1 192.168.0.101:80 check inter 3s fall 3 rise 5
server web2 192.168.0.102:80 check inter 3s fall 3 rise 5
...上面內容省略...
測試效果:
[Administrator.WIN-20240602BIS] ? for N in {1..6};do curl 172.25.254.100;done
RS1 server - 192.168.0.10
RS2 server - 192.168.0.20
RS1 server - 192.168.0.10
RS2 server - 192.168.0.20
RS1 server - 192.168.0.10
RS2 server - 192.168.0.20
3.3.2.5 Proxies配置-listen 簡化配置

使用listen替換 frontendbackend的配置方式,可以簡化設置,通常只用于TCP協議的應用

listen配置示例:

haproxy ~]# vim /etc/haproxy/haproxy.cfg
...上面內容省略...
listen webserver_80
bind 172.25.254.100:80
mode http
option forwardfor
server webserver1 192.168.0.101:80 check inter 3s fall 3 rise 5
server webserver2 192.168.0.102:80 check inter 3s fall 3 rise 5
...上面內容省略...

3.4.socat 工具:

對服務器動態權重和其它狀態可以利用 socat工具進行調整,Socat Linux 下的一個多功能的網絡工 具,名字來由是Socket CAT,相當于netCAT的增強版.Socat 的主要特點就是在兩個數據流之間建立雙向 通道,且支持眾多協議和鏈接方式。如 IPTCP UDPIPv6Socket文件等

范例:利用工具socat 對服務器動態權重調整

#修改配置文件
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
stats socket /var/lib/haproxy/stats mode 600 level admin
#查看幫助
haproxy ~]# socat -h
haproxy ~]# echo "help" | socat stdio /var/lib/haproxy/stats
The following commands are valid at this level:
help : this message
prompt : toggle interactive mode with prompt
quit : disconnect
。。。省略 。。。
enable server : enable a disabled server (use 'set server' instead) #啟用服務器
set maxconn server : change a server's maxconn setting
set server : change a server's state, weight or address #設置服務器
get weight : report a server's current weight #查看權重
set weight : change a server's weight (deprecated) #設置權重
show startup-logs : report logs emitted during HAProxy startup
how peers [peers section]: dump some information about all the peers or this
peers section
set maxconn global : change the per-process maxconn setting
set rate-limit : change a rate limiting value
set severity-output [none|number|string] : set presence of severity level in
feedback information
set timeout : change a timeout setting
show env [var] : dump environment variables known to the process
show cli sockets : dump list of cli sockets
show cli level : display the level of the current CLI session
show fd [num] : dump list of file descriptors in use
。。。省略 。。。
常用示例:
#查看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: 33542
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 webserver_80/webserver1 " | socat stdio
/var/lib/haproxy/stats
#上線后端服務器
[root@haproxy ~]# echo "enable server webserver_80/webserver1 " | socat stdio
/var/lib/haproxy/stats

針對多進程處理方法

如果開啟多進程那么我們在對進程的sock文件進行操作時其對進程的操作時隨機的

如果需要指定操作進程那么需要用多soct文件方式來完成

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月 8 13:43 stats
srw------- 1 root root 0 8月 8 13:46 stats1
srw------- 1 root root 0 8月 8 13:46 stats2

3.5 haproxy的狀態界面:

haproxy ~]# vim /etc/haproxy/haproxy.cfg
...上面內容省略...
listen stats
mode http
bind 0.0.0.0:8888
stats enable
log global
stats uri /haproxy-status
stats auth lee:lee
...下面內容省略...

3.6 haproxy的負載均衡集群簡單配置:

編輯haproxy配置文件?/etc/haproxy/haproxy.cfg

 82 frontend webcluster83     bind        *:8084     mode        http85     balance     roundrobin86     use_backend webserver8788 backend webserver89     server web1 172.25.254.10:8090     server web2 172.25.254.20:80

重啟服務并查看80端口:

[root@hp ~]# systemctl restart haproxy.service
[root@hp ~]# netstat -antlupe | grep 80
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      0          27935      1717/haproxy
udp        0      0 127.0.0.1:323           0.0.0.0:*                           0          22803      757/chronyd
udp6       0      0 ::1:323                 :::*                                0          22804      757/chronyd

客戶機上測試(記得關閉RS1 RS2防火墻并啟動服務)

[root@client ~]# for i in {1..10};do curl 172.25.254.50;done
RS1 - 172.25.254.10
RS2 - 172.25.254.20
RS1 - 172.25.254.10
RS2 - 172.25.254.20
RS1 - 172.25.254.10
RS2 - 172.25.254.20
RS1 - 172.25.254.10
RS2 - 172.25.254.20
RS1 - 172.25.254.10
RS2 - 172.25.254.20

.haproxy的算法

HAProxy通過固定參數 balance 指明對后端服務器的調度算法

balance參數可以配置在listenbackend選項中。

HAProxy的調度算法分為靜態和動態調度算法

有些算法可以根據參數在靜態和動態算法中相互轉換。

4.1 靜態算法:

靜態算法:按照事先定義好的規則輪詢公平調度,不關心后端服務器的當前負載、連接數和響應速度 等,且無法實時修改權重(只能為01,不支持其它值),只能靠重啟HAProxy生效。

4.1.1 static-rr:基于權重的輪詢調度

不支持運行時利用socat進行權重的動態調整(只支持01,不支持其它值)
不支持端服務器慢啟動
其后端主機數量沒有限制,相當于LVS中的 wrr
Note
慢啟動是指在服務器剛剛啟動上不會把他所應該承擔的訪問壓力全部給它,而是先給一部分,當沒
問題后在給一部分
示例:
haproxy ~]# vim /etc/haproxy/haproxy.cfg
...上面內容省略...
listen webserver_80
bind 172.25.254.100:80
mode http
balance static-rr
server webserver1 192.168.0.101:80 weight 2 check inter 3s fall 3 rise 5
server webserver2 192.168.0.102:80 weight 1 check inter 3s fall 3 rise 5
...上面內容省略...
4.1.2 first:

根據服務器在列表中的位置,自上而下進行調度

其只會當第一臺服務器的連接數達到上限,新請求才會分配給下一臺服務

其會忽略服務器的權重設置

不支持用socat進行動態修改權重,可以設置01,可以設置其它值但無效

示例:

haproxy ~]# vim /etc/haproxy/haproxy.cfg
...上面內容省略...
listen webserver_80
bind 172.25.254.100:80
mode http
balance first
server webserver1 192.168.0.101:80 maxconn 3 check inter 3s fall 3 rise 5
server webserver2 192.168.0.102:80 check inter 3s fall 3 rise 5
...上面內容省略...
測試效果:
#在兩臺主機上分別執行此循環,可以觀察是否102被調度到
while true;do curl 172.25.254.100 ; sleep 0.1;done

4.2 動態算法

動態算法
????????基于后端服務器狀態進行調度適當調整,
????????新請求將優先調度至當前負載較低的服務器
????????權重可以在haproxy運行時動態調整無需重啟
4.2.1 roundrobin
1. 基于權重的輪詢動態調度算法,
2. 支持權重的運行時調整,不同于lvs中的rr輪訓模式,
3. HAProxy中的roundrobin支持慢啟動(新加的服務器會逐漸增加轉發數)
4. 其每個后端backend中最多支持4095real server
5. 支持對real server權重動態調整,
6. roundrobin為默認調度算法,此算法使用廣泛
示例:
haproxy ~]# vim /etc/haproxy/haproxy.cfg
...上面內容省略...
listen webserver_80
bind 172.25.254.100:80
mode http
balance roundrobin
server webserver1 192.168.0.101:80 weight 1 check inter 3s fall 3 rise 5
server webserver2 192.168.0.102:80 weight 1 check inter 3s fall 3 rise 5
...上面內容省略...
動態調整權重
[root@haproxy ~]# echo "set weight webserver_80/webserver1 2" | socat stdio
/var/lib/haproxy/haproxy.sock
4.2.2 leastconn

leastconn加權的最少連接的動態

支持權重的運行時調整和慢啟動,即:根據當前連接最少的后端服務器而非權重進行優先調度(新客戶 端連接)

比較適合長連接的場景使用,比如:MySQL等場景。

示例:

haproxy ~]# vim /etc/haproxy/haproxy.cfg
...上面內容省略...
listen webserver_80
bind 172.25.254.100:80
mode http
balance leastconn
server webserver1 192.168.0.101:80 weight 1 check inter 3s fall 3 rise 5
server webserver2 192.168.0.102:80 weight 1 check inter 3s fall 3 rise 5
...上面內容省略
4.3 其他算法

其它算法即可作為靜態算法,又可以通過選項成為動態算法

4.3.1 source

源地址hash,基于用戶源地址hash并將請求轉發到后端服務器,后續同一個源地址請求將被轉發至同一 個后端web服務器。此方式當后端服務器數據量發生變化時,會導致很多用戶的請求轉發至新的后端服 務器,默認為靜態方式,但是可以通過hash-type支持的選項更改這個算法一般是在不插入CookieTCP 模式下使用,也可給拒絕會話cookie的客戶提供最好的會話粘性,適用于session會話保持但不支持 cookie和緩存的場景源地址有兩種轉發客戶端請求到后端服務器的服務器選取計算方式,分別是取模法 和一致性hash

haproxy ~]# vim /etc/haproxy/haproxy.cfg
...上面內容省略...
listen webserver_80
bind 172.25.254.100:80
mode http
balance source
server webserver1 192.168.0.101:80 weight 1 check inter 3s fall 3 rise 5
server webserver2 192.168.0.102:80 weight 1 check inter 3s fall 3 rise 5
...上面內容省略...[root@node10 ~]# for N in {1..6}; do curl 172.25.254.100; done
RS1 server - 192.168.0.101
RS1 server - 192.168.0.101
RS1 server - 192.168.0.101
RS1 server - 192.168.0.101
RS1 server - 192.168.0.101
RS1 server - 192.168.0.101
如果訪問客戶端時一個家庭,那么所有的家庭的訪問流量都會被定向到一臺服務器,這時source
法的缺陷
4.3.1.1 map-base 取模法

map-based:取模法,對source地址進行hash計算,再基于服務器總權重的取模,最終結果決定將此請 求轉發至對應的后端服務器。

此方法是靜態的,即不支持在線調整權重,不支持慢啟動,可實現對后端服務器均衡調度

缺點是當服務器的總權重發生變化時,即有服務器上線或下線,都會因總權重發生變化而導致調度結果 整體改變

hash-type 指定的默值為此算法

所謂取模運算,就是計算兩個數相除之后的余數,10%7=3, 7%4=3

map-based算法:基于權重取模,hash(source_ip)%所有后端服務器相加的總權重

比如當源hash值時111111121113,三臺服務器a b c的權重均為1
abc的調度標簽分別會被設定為 0 1 21111%3=11112%3=21113%3=0
1111 ----- > nodeb
1112 ------> nodec
1113 ------> nodea
如果a下線后,權重數量發生變化
1111%2=11112%2=01113%2=1
11121113被調度到的主機都發生變化,這樣會導致會話丟失

取模法配置示例:

haproxy ~]# vim /etc/haproxy/haproxy.cfg
...上面內容省略...
listen webserver_80
bind 172.25.254.100:80
mode http
balance source
server webserver1 192.168.0.101:80 weight 1 check inter 3s fall 3 rise 5
server webserver2 192.168.0.102:80 weight 1 check inter 3s fall 3 rise 5
...上面內容省略...
#不支持動態調整權重值
[root@haproxy ~]# echo "set weight webserver_80/webserver1 2" | socat stdio
/var/lib/haproxy/haproxy.sock
Backend is using a static LB algorithm and only accepts weights '0%' and '100%'.
#只能動態上線和下線
[root@haproxy ~]# echo "set weight webserver_80/webserver1 0" | socat stdio
/var/lib/haproxy/haproxy.sock
[root@haproxy ~]# echo "get weight webserver_80/webserver1" | socat stdio
/var/lib/haproxy/haproxy.sock
0 (initial 1)

4.3.1.2 一致性hash

一致性哈希,當服務器的總權重發生變化時,對調度結果影響是局部的,不會引起大的變動hasho) mod n

hash算法是動態的,支持使用 socat等工具進行在線權重調整,支持慢啟動

算法:

1、后端服務器哈希環點keyA=hash(后端服務器虛擬ip)%(2^32)

2、客戶機哈希環點key1=hash(client_ip)%(2^32) 得到的值在[0---4294967295]之間,

3、將keyAkey1都放在hash環上,將用戶請求調度到離key1最近的keyA對應的后端服務器

hash環偏斜問題

增加虛擬服務器IP數量,比如:一個后端服務器根據權重為1生成1000個虛擬IP,再hash。而后端服務器權
重為2則生成2000的虛擬IP,再bash,最終在hash環上生成3000個節點,從而解決hash環偏斜問題
hash對象
Hash對象到后端服務器的映射關系:

一致性hash示意圖

后端服務器在線與離線的調度方式

一致性hash配置示例
haproxy ~]# vim /etc/haproxy/haproxy.cfg
...上面內容省略...
listen webserver_80
bind 172.25.254.100:80
mode http
balance source
hash-type consistent
server webserver1 192.168.0.101:80 weight 1 check inter 3s fall 3 rise 5
server webserver2 192.168.0.102:80 weight 1 check inter 3s fall 3 rise 5
...上面內容省略...
4.3.2 uri
基于對用戶請求的URI的左半部分或整個urihash,再將hash結果對總權重進行取模后
根據最終結果將請求轉發到后端指定服務器
適用于后端是緩存服務器場景
默認是靜態算法,也可以通過hash-type指定map-basedconsistent,來定義使用取模法還是一致性 hash
Note
注意:此算法基于應用層,所以只支持 mode http ,不支持 mode tcp
<scheme>://<user>:<password>@<host>:<port>/<path>;<params>?<query>#<frag>
左半部分:/<path>;<params>
整個uri:/<path>;<params>?<query>#<frag>

4.3.2.1 uri 取模法配置示例
haproxy ~]# vim /etc/haproxy/haproxy.cfg
...上面內容省略...
listen webserver_80
bind 172.25.254.100:80
mode http
balance uri
server webserver1 192.168.0.101:80 weight 1 check inter 3s fall 3 rise 5
server webserver2 192.168.0.102:80 weight 1 check inter 3s fall 3 rise 5
...上面內容省略...
4.3.2.2 uri 一致性hash配置示例
haproxy ~]# vim /etc/haproxy/haproxy.cfg
...上面內容省略...
listen webserver_80
bind 172.25.254.100:80
mode http
balance uri
hash-type consistent
server webserver1 192.168.0.101:80 weight 1 check inter 3s fall 3 rise 5
server webserver2 192.168.0.102:80 weight 1 check inter 3s fall 3 rise 5
...上面內容省略..

4.3.2.3 訪問測試

訪問不同的uri,確認可以將用戶同樣的請求轉發至相同的服務器

root@rs1 ~]# echo RS1 192.168.0.101 index1 > /var/www/html/index1.html
[root@rs1 ~]# echo RS1 192.168.0.101 index2 > /var/www/html/index2.html
[root@rs1 ~]# echo RS1 192.168.0.101 index3 > /var/www/html/index3.html
[root@rs2 ~]# echo RS1 192.168.0.102 index1 > /var/www/html/index1.html
[root@rs2 ~]# echo RS1 192.168.0.102 index2 > /var/www/html/index2.html
[root@rs2 ~]# echo RS1 192.168.0.102 index3 > /var/www/html/index3.html
[root@node10 ~]# curl 172.25.254.100/index.html
RS2 server - 192.168.0.102
[root@node10 ~]# curl 172.25.254.100/index1.html
RS1 192.168.0.101 index1
[root@node10 ~]# curl 172.25.254.100/index2.html
RS1 192.168.0.102 index2
[root@node10 ~]# curl 172.25.254.100/index3.html
RS1 192.168.0.101 index3
4.3.3 url_param

url_param對用戶請求的url中的 params 部分中的一個參數key對應的value值作hash計算,并由服務器 總權重相除以后派發至某挑出的服務器,后端搜索同一個數據會被調度到同一個服務器,多用與電商

通常用于追蹤用戶,以確保來自同一個用戶的請求始終發往同一個real server

如果無沒key,將按roundrobin算法

#假設:
url = http://www.timinglee.com/foo/bar/index.php?key=value
#則:
host = "www.timinglee.com"
url_param = "key=value"
4.3.3.1 url_param取模法配置示例
haproxy ~]# vim /etc/haproxy/haproxy.cfg
...上面內容省略...
listen webserver_80
bind 172.25.254.100:80
mode http
balance url_param name,userid #支持對多個url_param hash
server webserver1 192.168.0.101:80 weight 1 check inter 3s fall 3 rise 5
server webserver2 192.168.0.102:80 weight 1 check inter 3s fall 3 rise 5
...上面內容省略...
4.3.3.2 url_param一致性hash配置示例
haproxy ~]# vim /etc/haproxy/haproxy.cfg
...上面內容省略...
listen webserver_80
bind 172.25.254.100:80
mode http
balance url_param name,userid #支持對多個url_param hash
hash-type consistent
server webserver1 192.168.0.101:80 weight 1 check inter 3s fall 3 rise 5
server webserver2 192.168.0.102:80 weight 1 check inter 3s fall 3 rise 5
...上面內容省略...
4.3.3.3 測試訪問
[root@node10 ~]# curl 172.25.254.100/index.html?name=timinglee
RS1 192.168.0.101 index3
[root@node10 ~]# curl 172.25.254.100/index.html?name=timinglee
RS1 192.168.0.101 index3
[root@node10 ~]# curl 172.25.254.100/index.html?userid=lee
RS1 192.168.0.102 index3
[root@node10 ~]# curl 172.25.254.100/index.html?userid=lee
RS1 192.168.0.102 index3
4.3.4 hdr

針對用戶每個http頭部(header)請求中的指定信息做hash

此處由 name 指定的http首部將會被取出并做hash計算,

然后由服務器總權重取模以后派發至某挑出的服務器,如果無有效值,則會使用默認的輪詢調度。

4.3.4.1 hdr取模法配置示例
haproxy ~]# vim /etc/haproxy/haproxy.cfg
...上面內容省略...
listen webserver_80
bind 172.25.254.100:80
mode http
balance hdr(User-Agent)
server webserver1 192.168.0.101:80 weight 1 check inter 3s fall 3 rise 5
server webserver2 192.168.0.102:80 weight 1 check inter 3s fall 3 rise 5
...上面內容省略...
4.3.4.2 一致性hash配置示例
haproxy ~]# vim /etc/haproxy/haproxy.cfg
...上面內容省略...
listen webserver_80
bind 172.25.254.100:80
mode http
balance hdr(User-Agent)
hash-type consistent
server webserver1 192.168.0.101:80 weight 1 check inter 3s fall 3 rise 5
server webserver2 192.168.0.102:80 weight 1 check inter 3s fall 3 rise 5
...上面內容省略.
4.3.4.3 測試訪問
[root@node10 ~]# curl -v 172.25.254.100
[root@node10 ~]# curl -vA "firefox" 172.25.254.100
[root@node10 ~]# curl -vA "sougou" 172.25.254.100
4.3.6 算法總結
#靜態
static-rr--------->tcp/http
first------------->tcp/http
#動態
roundrobin-------->tcp/http
leastconn--------->tcp/http
random------------>tcp/http
#以下靜態和動態取決于hash_type是否consistent
source------------>tcp/http
Uri--------------->http
url_param--------->http
hdr--------------->http
4.3.7 各算法使用場景
first #使用較少
static-rr #做了session共享的web集群
roundrobin
random
leastconn #數據庫
source
#基于客戶端公網IP的會話保持
Uri--------------->http #緩存服務器,CDN服務商,藍汛、百度、阿里云、騰訊
url_param--------->http #可以實現session保持
hdr #基于客戶端請求報文頭部做下一步處理

.高級功能及配置

5.1 基于cookie的會話保持

cookie value:為當前server指定cookie值,實現基于cookie的會話黏性,相對于基于 source 地址hash 調度算法對客戶端的粒度更精準,但同時也加大了haproxy負載,目前此模式使用較少, 已經被session 共享服務器代替

5.1.1 配置選項
cookie name [ rewrite | insert | prefix ][ indirect ] [ nocache ][ postonly ] [
preserve ][ httponly ] [ secure ][ domain ]* [ maxidle <idle> ][ maxlife ]
name: #cookie 的 key名稱,用于實現持久連接
insert: #插入新的cookie,默認不插入cookie
indirect: #如果客戶端已經有cookie,則不會再發送cookie信息
nocache: #當client和hapoxy之間有緩存服務器(如:CDN)時,不允許中間緩存器緩存cookie,
#因為這會導致很多經過同一個CDN的請求都發送到同一臺后端服務器
5.1.2 配置示例

配置文件:

 88 listen webcluster89     bind        *:8090     mode        http91     balance     roundrobin92     hash-type   consistent93     cookie WEBCOOKIE insert nocache indirect94     server web1 172.25.254.10:80 cookie servera  check inter 5s fall 395     server web2 172.25.254.20:80 cookie serverb  check inter 5s fall 3

重啟服務:

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

驗證:

5.2 HAProxy狀態頁:

5.2.1 狀態頁配置項
stats enable #基于默認的參數啟用stats page
stats hide-version #將狀態頁中haproxy版本隱藏
stats refresh <delay> #設定自動刷新時間間隔,默認不自動刷新
stats uri <prefix> #自定義stats page uri,默認值:/haproxy?stats
stats auth <user>:<passwd> #認證時的賬號和密碼,可定義多個用戶,每行指定一個用戶
#默認:no authentication
stats admin { if | unless } <cond> #啟用stats page中的管理功能
5.2.2 啟用狀態頁:
haproxy ~]# vim /etc/haproxy/haproxy.cfg
...上面內容省略...
listen stats:
mode http
bind 0.0.0.0:8888
stats enable
log global
stats uri /status #自定義stats page uri
stats auth lee:lee #認證,此行可以出現多次
...上面內容省略...
測試:
瀏覽器訪問:172.25.254.100:8888/status
5.2.3 登錄狀態頁
#pid為當前pid號,process為當前進程號,nbproc和nbthread為一共多少進程和每個進程多少個線程
pid = 27134 (process #1, nbproc = 1, nbthread = 1)
#啟動了多長時間
uptime = 0d 0h00m04s
#系統資源限制:內存/最大打開文件數/
system limits: memmax = unlimited; ulimit-n = 200029
#最大socket連接數/單進程最大連接數/最大管道數maxpipes
maxsock = 200029; maxconn = 100000; maxpipes = 0
#當前連接數/當前管道數/當前連接速率
current conns = 2; current pipes = 0/0; conn rate = 2/sec; bit rate = 0.000 kbps
5.2.4 backend server信息
session rate(每秒的連接會話信息): Errors(錯誤統計信息):
cur:每秒的當前會話數量 : Req:錯誤請求量
max:每秒新的最大會話數量 conn:錯誤鏈接量
limit:每秒新的會話限制量 Resp:錯誤響應量
sessions(會話信息): Warnings(警告統計信息):
cur:當前會話量 Retr:重新嘗試次數
max:最大會話量 Redis:再次發送次數
limit: 限制會話量
Total:總共會話量 Server(real server信息):
LBTot:選中一臺服務器所用的總時間 Status:后端機的狀態,包括UP和DOWN
Last:和服務器的持續連接時間 LastChk:持續檢查后端服務器的時間
Wght:權重
Bytes(流量統計): Act:活動鏈接數量
In:網絡的字節輸入總量 Bck:備份的服務器數量
Out:網絡的字節輸出總量 Chk:心跳檢測時間
Dwn:后端服務器連接后都是DOWN的數量
Denied(拒絕統計信息): Dwntme:總的downtime時間
Req:拒絕請求量 Thrtle:server 狀態
Resp:拒絕回復量
5.3 IP透傳
web服務器中需要記錄客戶端的真實IP地址,用于做訪問統計、安全防護、行為分析、區域排行等場景。
#運行的任務/當前空閑率
Running tasks: 1/14; idle = 100 %
active UP: #在線服務器
backup UP: #標記為backup的服務器
active UP, going down: #監測未通過正在進入down過程
backup UP, going down: #備份服務器正在進入down過程
active DOWN, going up: #down的服務器正在進入up過程
backup DOWN, going up: #備份服務器正在進入up過程
active or backup DOWN: #在線的服務器或者是backup的服務器已經轉換成了down狀態
not checked: #標記為不監測的服務器
#active或者backup服務器人為下線的
active or backup DOWN for maintenance (MAINT)
#active或者backup被人為軟下線(人為將weight改成0)
active or backup SOFT STOPPED for maintenance

5.2.4 backend server信息

session rate(每秒的連接會話信息): ????????????????Errors(錯誤統計信息):

cur:每秒的當前會話數量 : ???????????????????????????????Req:錯誤請求量

max:每秒新的最大會話數量?????????????????????????????conn:錯誤鏈接量

limit:每秒新的會話限制量 ????????????????????????????????Resp:錯誤響應量

sessions(會話信息):? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?Warnings(警告統計信息):

cur:當前會話量????????????????????????????????????????????????Retr:重新嘗試次數

max:最大會話量??????????????????????????????????????????????Redis:再次發送次數

limit: 限制會話量? ???????????????????????????????????????????Total:總共會話量

Server(real server信息): ??????????????????????????????LBTot:選中一臺服務器所用的總間????????????????

Status:后端機的狀態,包括UP和DOWN ???????Last:和服務器的持續連接時間

LastChk:持續檢查后端服務器的時間? ? ? ? ? ? ? Wght:權重

Bytes(流量統計):? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? Act:活動鏈接數量

In:網絡的字節輸入總量? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?Bck:備份的服務器數量

Out:網絡的字節輸出總量????????????????????????????????Chk:心跳檢測時間

Dwn:后端服務器連接后都是DOWN的數量? ? ?Denied(拒絕統計信息)

Dwntme:總的downtime時間? ? ? ? ? ? ? ? ? ? ? ? ? ?Req:拒絕請求量

Thrtle:server 狀態 ?????????????????????????????????????????Resp:拒絕回復量

5.3 IP透傳:

web服務器中需要記錄客戶端的真實IP地址,用于做訪問統計、安全防護、行為分析、區域排行等場景

5.3.2 四層IP透傳
修改nginx配置文件(RS1 RS2)

修改haproxy配置文件

測試:

5.3.3 七層IP透傳:

haproxy工作在七層的時候,也可以透傳客戶端真實IP至后端服務器

七層默認開啟ip透傳

5.4 ACL:

訪問控制列表ACLAccess Control Lists
是一種基于包過濾的訪問控制技術
它可以根據設定的條件對經過服務器傳輸的數據包進行過濾(條件匹配)即對接收到的報文進行匹配和過 濾,基于請求報文頭部中的源地址、源端口、目標地址、目標端口、請求方法、URL、文件后綴等信息內 容進行匹配并執行進一步操作,比如允許其通過或丟棄。
#示例
frontend test_acl
bind *:80
mode http
#acl bad_browers hdr_beg(User-Agent) -i curl
#http-request deny if bad_browers
#acl test hdr_dom(host) -i www.timinglee.org
#acl test hdr_end(host) -i .org
#acl test base_sub -m sub org
#acl test path_sub -m sub /a
#acl test path_end -m sub /a
#acl test path_reg -i ^/t
acl test url_sub -m sub lee
acl test path_dir -m sub a
use_backend test_web if test
default_backend default_webserver
backend default_webserver
mode http
server web1 172.25.254.20:80 check inter 3 fall 3 rise 5
backend test_web
mode http
server web2 172.25.254.30:80 check inter 3 fall 3 rise 5
5.4.1 ACL配置選項
#用acl來定義或聲明一個acl
acl <aclname> <criterion> [flags] [operator] [<value>]
acl 名稱 匹配規范 匹配模式 具體操作符 操作對象類型
5.4.1.1 ACL-Name 名稱
acl test path_end -m sub /a
#ACL名稱,可以使用大字母A-Z、小寫字母a-z、數字0-9、冒號:、點.、中橫線和下劃線,并且嚴格區分大
小寫,比如:my_acl和My_Acl就是兩個完全不同的acl5.8.1.2 ACL-criterion
5.4.1.2 ACL-criterion 匹配規范

定義ACL匹配規范,即:判斷條件

整數比較:eq、ge、gt、le、lt
字符比較:
- exact match (-m str) :字符串必須完全匹配模式
- substring match (-m sub) :在提取的字符串中查找模式,如果其中任何一個被發現,ACL將匹配
- prefix match (-m beg) :在提取的字符串首部中查找模式,如果其中任何一個被發現,ACL將匹配
- suffix match (-m end) :將模式與提取字符串的尾部進行比較,如果其中任何一個匹配,則ACL進行
匹配
- subdir match (-m dir) :查看提取出來的用斜線分隔(“/")的字符串,如其中任一個匹配,則ACL
進行匹配
- domain match (-m dom) :查找提取的用點(“.")分隔字符串,如果其中任何一個匹配,則ACL進行
匹配
5.4.1.3 ACL-flags 匹配模式
ACL匹配模式
-i 不區分大小寫
-m 使用指定的正則表達式匹配方法
-n 不做DNS解析
-u 禁止acl重名,否則多個同名ACL匹配或關系
5.4.1.4 ACL-operator 具體操作符

ACL 操作符

整數比較:eq、ge、gt、le、lt
字符比較:
- exact match (-m str) :字符串必須完全匹配模式
- substring match (-m sub) :在提取的字符串中查找模式,如果其中任何一個被發現,ACL將匹配
- prefix match (-m beg) :在提取的字符串首部中查找模式,如果其中任何一個被發現,ACL將匹配
- suffix match (-m end) :將模式與提取字符串的尾部進行比較,如果其中任何一個匹配,則ACL進行
匹配
- subdir match (-m dir) :查看提取出來的用斜線分隔(“/")的字符串,如其中任一個匹配,則ACL
進行匹配
- domain match (-m dom) :查找提取的用點(“.")分隔字符串,如果其中任何一個匹配,則ACL進行
匹配
5.4.1.5 ACL-value 操作對象
value的類型
The ACL engine can match these types against patterns of the following types :
- Boolean #布爾值
- integer or integer range #整數或整數范圍,比如用于匹配端口范圍
- IP address / network #IP地址或IP范圍, 192.168.0.1 ,192.168.0.1/24
- string--> www.timinglee.org
exact #精確比較
substring #子串
suffix #后綴比較
prefix #前綴比較
subdir #路徑, /wp-includes/js/jquery/jquery.js
domain #域名,www.timinglee.org
- regular expression #正則表達式
- hex block #16進制
5.4.2 多個ACL的組合調用方式
多個ACL的邏輯處理
與:隱式(默認)使用
或:使用“or" 或 “||"表示
否定:使用 "!" 表示
多個ACL調用方式:
#示例:
if valid_src valid_port #與關系,ACL中A和B都要滿足為true,默認為與
if invalid_src || invalid_port #或,ACL中A或者B滿足一個為true
if ! invalid_src #非,取反,不滿足ACL才為true
5.4.3 ACL示例-域名匹配
haproxy ~]# vim /etc/haproxy/haproxy.cfg
...上面內容省略...
frontend testacl
bind :80
mode http
########### ACL settings #######################
acl web_host hdr_dom(host) www.timinglee.org
########### host ###########################
use_backend timinglee_host if web_host
########### default server ###################
default_backend default_webserver
backend timinglee_host
mode http
server web1 192.168.0.101:80 check weight 1 inter 3s fall 3 rise 5
server web2 192.168.0.102:80 check weight 1 inter 3s fall 3 rise 5
backend default_webserver
mode http
server web1 172.25.254.10:80 check weight 1 inter 3s fall 3 rise 5
...上面內容省略...
測試結果:
#在瀏覽器所在主機中做地址解析
[root@node10 html]# vim /etc/hosts
172.25.254.100 www.timinglee.org
#測試結果
[root@node10 html]# curl www.timinglee.org
RS1 192.168.0.101
[root@node10 html]# curl www.timinglee.org
RS2 server - 192.168.0.102
[root@node10 html]# curl 172.25.254.100
default web server node10
5.4.4 ACL示例-基于源IP或子網調度訪問
將指定的源地址調度至指定的web服務器組。
haproxy ~]# vim /etc/haproxy/haproxy.cfg
...上面內容省略...
測試結果
5.4.5 ACL示例-基于源地址的訪問控制
拒絕指定IP或者IP范圍訪問
frontend testacl
bind :80
mode http
########### ACL settings #######################
acl ip_test src 172.25.254.1 192.168.0.0/24
########### host ###########################
use_backend ip_test-host if ip_test
########### default server ###################
default_backend default_webserver
backend ip_test-host
mode http
server web1 192.168.0.101:80 check weight 1 inter 3s fall 3 rise 5
backend default_webserver
mode http
server web1 172.25.254.10:80 check weight 1 inter 3s fall 3 rise 5
#測試結果
[172.25.254.10 root@node10 html]# curl 172.25.254.100
default web server node10
[172.25.254.1 Administrator.WIN-20240602BIS] ? curl 172.25.254.100
RS1 192.168.0.101
[192.168.0.102 root@rs1 ~]# curl 192.168.0.101
RS1 192.168.0.101
5.4.5 ACL示例-基于源地址的訪問控制

拒絕指定IP或者IP范圍訪問

haproxy ~]# vim /etc/haproxy/haproxy.cfg
...上面內容省略...
frontend testacl
bind :80
mode http
########### ACL settings #######################
acl web_host hdr_dom(host) www.timinglee.org
acl ip_test src 172.25.254.1 192.168.0.0/24
########### host ###########################
http-request deny if web_host
########### default server ###################
default_backend default_webserver
backend ip_test-host
mode http
server web1 192.168.0.101:80 check weight 1 inter 3s fall 3 rise 5
backend default_webserver
mode http
server web1 172.25.254.10:80 check weight 1 inter 3s fall 3 rise 5
測試
[root@node10 ~]# curl www.timinglee.org
<html><body><h1>403 Forbidden</h1>
Request forbidden by administrative rules.
</body></html>
[root@node10 ~]# curl 172.25.254.100
default web server node10
5.4.6 ACL示例-匹配瀏覽器類型

匹配客戶端瀏覽器,將不同類型的瀏覽器調動至不同的服務器組、

范例: 拒絕curlwget的訪問

示例:

haproxy ~]# vim /etc/haproxy/haproxy.cfg
...上面內容省略...
frontend testacl
bind :80
mode http
########### ACL settings #######################
acl user_agent_block hdr_sub(User-Agent) -i curl wget
acl user_agent_redirect hdr_sub(User-Agent) -i Mozilla/5.0
########### host ###########################
http-request deny if user_agent_block
redirect prefix https://www.baidu.com if user_agent_redirect
########### default server ###################
default_backend default_webserver
backend ip_test-hostmode http
server web1 192.168.0.101:80 check weight 1 inter 3s fall 3 rise 5
backend default_webserver
mode http
server web1 172.25.254.10:80 check weight 1 inter 3s fall 3 rise 5
測試:1。
[root@node10 ~]# curl 172.25.254.100
<html><body><h1>403 Forbidden</h1>
Request forbidden by administrative rules.
</body></html>
2.
[root@node10 ~]# wget http://172.25.254.100/index.html
--2024-07-11 23:04:36-- http://172.25.254.100/index.html
Connecting to 172.25.254.100:80... connected.
HTTP request sent, awaiting response... 403 Forbidden
2024-07-11 23:04:36 ERROR 403: Forbidden.
3.瀏覽器中測試
5.4.7 ACL示例-基于文件后綴名實現動靜分離
haproxy ~]# vim /etc/haproxy/haproxy.cfg
...上面內容省略...
frontend testacl
bind :80
mode http
########### ACL settings #######################
acl url_static path_end -i .jpg .png .css .js .html
acl url_php path_end -i .php
########### host ###########################
use_backend static_host if url_static
use_backend php_host if url_php
########### default server ###################
default_backend default_webserver
backend static_host
mode http
server web2 192.168.0.101:80 check weight 1 inter 3s fall 3 rise 5
backend php_host
mode http
server web1 192.168.0.102:80 check weight 1 inter 3s fall 3 rise 5backend default_webserver
mode http
server web1 172.25.254.10:80 check weight 1 inter 3s fall 3 rise 5測試:
[root@rs1 ~]# echo css 192.168.0.101 > /usr/share/nginx/html/index.css
[root@rs2 ~]# echo php 192.168.0.102 > /var/www/html/index.php
[root@node10 ~]# curl 172.25.254.100/index.php
php 192.168.0.102
[root@node10 ~]# curl 172.25.254.100/index.css
css 192.168.0.101
5.4.8 ACL-匹配訪問路徑實現動靜分離
haproxy ~]# vim /etc/haproxy/haproxy.cfg
...上面內容省略...
frontend testacl
bind :80
mode http
########### ACL settings #######################
acl url_static path_end -i .jpg .png .css .js .html
acl url_static path_end -m sub /static /images /javascript
acl acl_app path_beg -m sub /api
########### host ###########################
use_backend static_host if url_static
use_backend api_host if acl_app
########### default server ###################
default_backend default_webserver
backend static_host
mode http
server web2 192.168.0.101:80 check weight 1 inter 3s fall 3 rise 5
backend api_host
mode http
server web1 192.168.0.102:80 check weight 1 inter 3s fall 3 rise 5
backend default_webserver
mode http
server web1 172.25.254.10:80 check weight 1 inter 3s fall 3 rise 5#創建相關文件
[root@rs1 ~]# mkdir /usr/share/nginx/html/static
[root@rs1 ~]# echo static 192.168.0.101 > /usr/share/nginx/html/static/index.html
[root@rs2 ~]# mkdir /var/www/html/api/
[root@rs2 ~]# echo api 192.168.0.102 > /var/www/html/api/index.html
#測試訪問
[root@node10 ~]# curl 172.25.254.100/api/
api 192.168.0.102
[root@node10 ~]# curl 172.25.254.100/static/
static 192.168.0.101

5.5 自定義HAProxy 錯誤界面

對指定的報錯進行重定向,進行優雅的顯示錯誤頁面
使用errorfileerrorloc指令的兩種方法,可以實現自定義各種錯誤頁面
haproxy ~]# vim /etc/haproxy/haproxy.cfg
...上面內容省略...
defaults
測試:
5.5.2 基于http重定向錯誤頁面
范例:
mode http
...內容省略...
timeout client 1m
timeout server 1m
timeout http-keep-alive 10s
timeout check 10s
maxconn 1000000
errorfile 503 /haproxy/errorpages/503page.http
[root@haproxy ~]# mkdir /haproxy/errorpages/ -p
[root@haproxy ~]# cp /usr/share/haproxy/503.http /haproxy/errorpages/503page.http
[root@haproxy ~]# vim /haproxy/errorpages/503page.http
HTTP/1.0 503 Service Unavailable
Cache-Control: no-cache
Connection: close
Content-Type: text/html;charset=UTF-8^M
<html><body><h1>什么動物生氣最安靜</h1>
大猩猩!!
</body></html>
關閉后端的RS主機
然后用瀏覽器去訪問172.25.254.100
5.5.1?基于http重定向錯誤頁面
#錯誤頁面重定向
errorloc <code> <url>
#相當于errorloc302 <code> <url>,利用302重定向至指URL
#示例:
errorloc 503 https://www.baidu.com
haproxy ~]# vim /etc/haproxy/haproxy.cfg
...上面內容省略...
defaults
mode http
...內容省略...
timeout client 1m
timeout server 1m
timeout http-keep-alive 10s
timeout check 10s
5.6 HAProxy 四層負載
針對除HTTP以外的TCP協議應用服務訪問的應用場景
四層負載示例
注意:如果使用frontend和backend,一定在 frontend 和 backend 段中都指定mode tcp 
范例:對 MySQL 服務實現四層負載
maxconn 1000000
errorloc 503 https://www.baidu.com
#瀏覽器訪問172.25.254.100 自動跳轉到百度

5.6 HAProxy 四層負載

針對除HTTP以外的TCP協議應用服務訪問的應用場景

MySQL

Redis

Memcache

RabbitMQ

首先在RS1 RS2 中下載

mariadb
rs1 ~]# yum install mariadb-server -y
rs2 ~]# yum install mariadb-server -y

給數據庫加id

rs1 ~]# systemctl start mariadb
rs2 ~]# systemctl start mariadb
rs1 ~]# mysql -e "grant all on *.* to lee@'%' identified by 'lee';"
rs2 ~]# mysql -e "grant all on *.* to lee@'%' identified by 'lee';"

haproxy做四層負載(修改配置文件)并重啟服務:

測試:

客戶端安裝mariadb

[root@client ~]# dnf install mariadb -y

5.7 HAProxy https 實現

haproxy可以實現https的證書安全,從用戶到haproxyhttps,haproxy到后端服務器用http通信
但基于性能考慮,生產中證書都是在后端服務器比如nginx上實現
#配置HAProxy支持https協議,支持ssl會話;
bind *:443 ssl crt /PATH/TO/SOME_PEM_FILE
#指令 crt 后證書文件為PEM格式,需要同時包含證書和所有私鑰
cat demo.key demo.crt > demo.pem
#把80端口的請求重向定443
bind *:80
redirect scheme https if !{ ssl_fc }
5.7.1 證書制作
haproxy ~]# mkdir /etc/haproxy/certs/
haproxy ~]# openssl req -newkey rsa:2048 \
-nodes -sha256 –keyout /etc/haproxy/certs/timinglee.org.key \
-x509 -days 365 -out /etc/haproxy/certs/timinglee.org.crt
5.7.2 https配置示例
haproxy ~]# vim /etc/haproxy/haproxy.cfg
frontend webserver
bind *:80
redirect scheme https if !{ ssl_fc }
mode http
use_backend webcluster
frontend webserver-https
bind *:443 ssl crt /etc/haproxy/timinglee.org.pem
mode http
use_backend webcluster
backend webcluster
mode http
balance roundrobin
server web1 172.25.254.200:80 check inter 3s fall 3 rise 5
server web2 172.25.254.201:80 check inter 3s fall 3 rise 5

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/pingmian/90379.shtml
繁體地址,請注明出處:http://hk.pswp.cn/pingmian/90379.shtml
英文地址,請注明出處:http://en.pswp.cn/pingmian/90379.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

【STM32項目】智能家居(版本1)

????大家好&#xff0c;這里是5132單片機畢設設計項目分享&#xff0c;今天給大家分享的是基于《基于STM32的智能家居設計》。 目錄 1、系統功能 2.1、硬件清單 2.2、功能介紹 2.3、控制模式 2、演示視頻和實物 3、系統設計框圖 4、軟件設計流程圖 5、原理圖 6、主…

OpenSCA開源社區每日安全漏洞及投毒情報資訊—2025年7月24日

2025年7月24日安全風險情報資訊在野漏洞風險&#xff08;CVE未收錄&#xff09;&#xff1a;1公開漏洞精選&#xff1a;2組件投毒情報&#xff1a;2在野漏洞風險&#xff08;CVE未收錄&#xff09;1.1 gemini-cli項目潛在命令注入漏洞項目詳情項目描述&#xff1a;gemini-cli是…

飛算 JavaAI 深度實戰:從老項目重構到全棧開發的降本增效密碼

飛算 JavaAI 深度實戰&#xff1a;從老項目重構到全棧開發的降本增效密碼引言正文一、智能引導模塊&#xff1a;老項目重構的 “手術刀” 級解決方案1.1 本地化智能分析&#xff1a;IDEA 插件實操演示1.1.1 &#x1f4cc; IDEA 插件安裝步驟1.1.1.1 首先打開idea工具&#xff0…

分布式推客系統開發全解:微服務拆分、傭金結算與風控設計

一、推客系統概述與市場背景推客系統&#xff08;也稱為分銷系統或社交電商系統&#xff09;已成為現代電商平臺和內容平臺的重要增長引擎。根據最新統計數據&#xff0c;2023年社交電商市場規模已突破3萬億元&#xff0c;占整體電商市場份額的25%以上。推客系統的核心價值在于…

Linux tcpdump 抓取udp 報文

一、tcpdump 支持命令選項tcpdump -i # 指定監聽網絡接口tcpdump -w # 將捕獲到的信息保存到文件中&#xff0c;且不分析和打印在屏幕tcpdump -r # 從文件中讀取數據tcpdump -n # 不把 ip 轉化成域名tcpdump -t # 在每行的輸出中不顯示時間tcpdump -v # 產生詳細的輸出tc…

Oracle數據塊8KB、OS默認認塊管理4KB,是否需調整大小為一致?

上班路上&#xff0c;腦中忽然閃現一個問題&#xff1a;Oracle數據庫塊大小&#xff08;8KB&#xff09;、操作系統文件系統塊大小&#xff08;4KB&#xff09;&#xff0c;為了減少IOPS&#xff0c;需不需要調整為一致&#xff1f;在數據塊保持一致的情況下&#xff0c;針對頻…

卡爾曼濾波器噪聲方差設置對性能影響的仿真研究

卡爾曼濾波器噪聲方差設置對性能影響的仿真研究 前些天發現了一個巨牛的人工智能學習網站,通俗易懂,風趣幽默,忍不住分享一下給大家,覺得好請收藏。點擊跳轉到網站。 1. 引言 卡爾曼濾波器是一種廣泛應用于信號處理、控制系統、導航系統等領域的遞歸估計算法。它通過對系…

“多線程修路:當count++變成災難現場”

1.現象 當我們操作一個線程池的時候&#xff0c;可能需要去計數&#xff0c;也就是統計count&#xff0c;那我們這里有一個疑問&#xff0c;會不會產生線程安全問題&#xff1f; 毫無疑問絕對會有線程安全問題。在線程池環境中&#xff0c;多個線程并發訪問和修改一個共享的 co…

GaussDB null的用法

1 null的定義null 空值代表丟失的未知數據。 默認情況下&#xff0c;表列可以保存 null 值。 本章解釋 is null 和 is not null 操作符。2 null值的贅述如果表中的列是可選的&#xff0c;那么我們可以插入一個新記錄或更新一個現有記錄&#xff0c;而無 需向列添加一個值。這意…

智慧農業新圖景:物聯網如何精準守護作物生長?

在傳統農業生產模式下&#xff0c;農民往往憑借經驗判斷作物生長需求&#xff0c;灌溉、施肥缺乏精準性&#xff0c;導致水資源浪費、土壤板結、作物產量與品質難以提升等問題。加之氣候變化無常&#xff0c;極端天氣頻發&#xff0c;給農業生產帶來諸多不確定性&#xff0c;傳…

[ComfyUI] -入門2- 小白零基礎搭建ComfyUI圖像生成環境教程

AI圖像生成已經成為AIGC(人工智能生成內容)領域的重要組成部分,而ComfyUI作為一款可視化的Stable Diffusion工作流工具,以其模塊化、高度自由化的特點吸引了越來越多創作者的關注。本文將手把手教你如何在Windows系統下,從零搭建屬于自己的ComfyUI圖像生成環境。 一、Comf…

java設計模式 -【單例模式】

單例模式的定義 單例模式&#xff08;Singleton Pattern&#xff09;是一種創建型設計模式&#xff0c;確保一個類只有一個實例&#xff0c;并提供一個全局訪問點。常用于需要控制資源或共享狀態的場景&#xff0c;例如數據庫連接、日志記錄器等 單例模式的實現方式 餓漢式&…

Flink 自定義類加載器和子優先類加載策略

子類優先加載Flink 默認采用了子優先&#xff08;Child-First&#xff09;的類加載策略來加載用戶代碼&#xff0c;以解決潛在的依賴沖突問題。我們可以通過源碼來證明這一點。ChildFirstClassLoader 的實現Flink 中負責實現“子優先”加載邏輯的核心類是 ChildFirstClassLoade…

Nginx 安全加固:如何阻止 IP 直接訪問,只允許域名訪問

在部署網站或 Web 應用時,我們通常會通過域名來訪問服務。然而,有時用戶可能會嘗試直接使用服務器的 IP 地址來訪問,這不僅可能繞過我們的域名特定配置(如 SSL 證書、重定向規則等),還可能導致不必要的安全風險或管理混亂。本文將介紹如何配置 Nginx,使其在通過 IP 地址…

服務端處于 TIME_WAIT 狀態的 TCP 連接,收到相同四元組的 SYN 后會發生什么?詳解

文章目錄一、先判斷 SYN 是否合法1、開啟「時間戳」機制1.1、合法 SYN1.2、非法 SYN2、關閉「時間戳」機制1.1、合法 SYN1.2、非法 SYN二、收到合法 SYN三、收到非法 SYN一、先判斷 SYN 是否合法 1、開啟「時間戳」機制 1.1、合法 SYN 客戶端的 SYN「序列號」比服務端「期望…

數字化轉型:一文讀懂從單系統到智能架構(業務、應用、數據、技術架構)的跨越

在數字化浪潮席卷全球的今天&#xff0c;企業正經歷從 “單系統孤島” 到 “智能架構協同” 的范式革命。智能架構以業務敏捷化、應用服務化、數據價值化、技術云原生化為核心特征&#xff0c;通過四個維度的架構升級&#xff0c;破解傳統 IT 系統的效率瓶頸&#xff0c;支撐企…

AUTOSAR進階圖解==>AUTOSAR_SRS_Transformer

AUTOSAR Transformer 詳解 基于AUTOSAR 4.4.0標準的Transformer模塊分析與說明目錄 1. Transformer概述 1.1 Transformer的作用1.2 Transformer的基本特性 2. Transformer架構 2.1 整體架構2.2 類層次結構 3. Transformer類型 3.1 SOME/IP Transformer3.2 COM Based Transform…

【算法專題訓練】05、最大單詞長度乘積

1、題目信息 https://leetcode.cn/problems/aseY1I/description/ 給定一個字符串數組 words&#xff0c;請計算當兩個字符串 words[i] 和 words[j] 不包含相同字符時&#xff0c;它們長度的乘積的最大值。假設字符串中只包含英語的小寫字母。如果沒有不包含相同字符的一對字符串…

Tenable 利用 AI 升級漏洞評級系統,提升風險優先級排序能力

網絡安全公司 Tenable Holdings Inc. 今日宣布對其漏洞優先級評級系統&#xff08;Vulnerability Priority Rating&#xff0c;VPR&#xff09;進行人工智能驅動的升級&#xff0c;旨在幫助機構更準確地識別和應對最具威脅性的漏洞。從60%到1.6%的精準聚焦Tenable VPR 系統于20…

安全插座項目規劃書

安全插座項目規劃書 一、項目概述 本項目旨在設計并開發一款安全插座&#xff0c;通過集成多種安全保護功能&#xff0c;有效預防因電氣故障引發的安全問題&#xff0c;如過載、短路、漏電等&#xff0c;為用戶提供更加可靠的用電環境。 二、技術架構 &#xff08;一&#xff0…