首先來簡單認識一下 HaProxy :一款提供高可用性、負載均衡以及基於TCP(第四層)和HTTP(第七層)應用的代理軟件,支持虛擬主機,是免費、快速而且可靠的一種解決方案。HAProxy 的實現基於事件驅動、單一進程模型,相似 Node.js 的進程模型,可以支撐很是大的併發鏈接數. html
如下實驗環境均爲 CentOS7 平臺。 還須要兩個 MySQL 實例,端口分別爲3311,3312.linux
1.首先從官網上下載穩定版本 haproxy-1.9.2.tar,經過 FTP 工具傳至服務器.git
2.解壓 haproxy-1.9.2.tar,並進入解壓後的文件夾github
tar -xvf haproxy-1.9.2.tar && cd haproxy-1.9.2
複製代碼
3.因爲壓縮出來的是 haproxy 的源文件,因此還須要經過本地編譯安裝redis
make TARGET=generic # 指定編譯的目標平臺爲通用
make install
複製代碼
安裝完成以後目錄下文件就多了一些關於 haProxy 的文件算法
直接使用指令 haproxy
就是檢查 Haproxy 是否安裝成功.shell
[root@izm5e2w1juq9po7368cfj1z haproxy-1.9.2]# haproxy
HA-Proxy version 1.9.2 2019/01/16 - https://haproxy.org/
Usage : haproxy [-f <cfgfile|cfgdir>]* [ -vdVD ] [ -n <maxconn> ] [ -N <maxpconn> ]
[ -p <pidfile> ] [ -m <max megs> ] [ -C <dir> ] [-- <cfgfile>*]
-v displays version ; -vv shows known build options.
-d enters debug mode ; -db only disables background mode.
-dM[<byte>] poisons memory with <byte> (defaults to 0x50)
-V enters verbose mode (disables quiet mode)
-D goes daemon ; -C changes to <dir> before loading files.
-W master-worker mode.
-q quiet mode : don't display messages
-c check mode : only check config files and exit
-n sets the maximum total # of connections (2000)
-m limits the usable amount of memory (in MB)
-N sets the default, per-proxy maximum # of connections (2000)
-L set local peer name (default to hostname)
-p writes pids of all children to this file
-dp disables poll() usage even when available
-dR disables SO_REUSEPORT usage
-dr ignores server address resolution failures
-dV disables SSL verify on servers side
-sf/-st [pid ]* finishes/terminates old pids.
-x <unix_socket> get listening sockets from a unix socket
-S <unix_socket>[,<bind options>...] new stats socket for the master
複製代碼
4.爲 HaProxy 添加配置文件,命名爲 haproxy.confbash
global
daemon # 後臺方式運行
nbproc 1
pidfile haproxy.pid
defaults
mode tcp #默認的模式mode { tcp|http|health },tcp是4層,http是7層,health只會返回OK
retries 2 #兩次鏈接失敗就認爲是服務器不可用,也能夠經過後面設置
option redispatch #當serverId對應的服務器掛掉後,強制定向到其餘健康的服務器
option abortonclose #當服務器負載很高的時候,自動結束掉當前隊列處理比較久的連接
maxconn 4096 #默認的最大鏈接數
timeout connect 5000ms #鏈接超時
timeout client 30000ms #客戶端超時
timeout server 30000ms #服務器超時
#timeout check 2000 #=心跳檢測超時
log 127.0.0.1 local0 err #[err warning info debug]
balance roundrobin # 採用輪詢算法
################# 配置#################
listen delegate #這裏是配置負載均衡,test1是名字,能夠任意
bind 0.0.0.0:3306 #這裏是監聽的IP地址和端口,端口號能夠在0-65535之間,要避免端口衝突
mode tcp #鏈接的協議,這裏是tcp協議
#maxconn 4086
#log 127.0.0.1 local0 debug
server s1 localhost:3312 #負載的MySQL實例1
server s2 localhost:3311 #負載的MySQL實例2 能夠有多個,往下排列即
複製代碼
具體配置參數說明可參考 HaProxy 官網的配置案例服務器
HaProxy 負載算法 HaProxy 支持多種負載算法,能夠經過在配置文件中 balance
指定.cookie
5.加載配置文件方式啓動 HaProxy
haproxy -f conf/haproxy.conf
複製代碼
爲了檢驗 MySQL 的負載均衡是否生效,咱們能夠簡單地使用 MySQL 客戶端工具來鏈接試下,首先在兩個 MySQL 實例中各自新建一個不一樣名字的庫,端口爲3311建立 salve, 端口爲3312的建立 salve11.