Haproxy 四層負載均衡
拓撲:
app ----> mysql_master(write)
|
haproxy(read)
|
mysql_slave*N
一 Haproxy 部分
1 haproxy 代碼mysql
- listen bbs_slave 10.0.100.82:3306
- mode tcp #配置TCP模式
- maxconn 2000
- balance roundrobin
- #option httpchk OPTIONS * HTTP/1.1\r\nHost:\ www
- server slave01 10.0.100.75:3306 check port 9120 inter 5000 rise 3 fall 3 weight 3
- server slave02 10.0.100.76:3306 check port 9120 inter 5000 rise 3 fall 3 weight 3
- srvtimeout 20000
二 Mysql 部分
2.1 mysql replication 監控腳本linux
- cat /usr/local/bin/mysqlrep_status.sh
- #!/bin/bash
- #
- # /usr/local/bin/mysqlrep_status.sh
- #
- # This script checks if a mysql server is healthy running on localhost. It will
- # return:
- #
- # "HTTP/1.x 200 OK\r" (if mysql is running smoothly)
- #
- # – OR –
- #
- # "HTTP/1.x 503 Internal Server Error\r" (else)
- #
- mysql=/usr/local/bin/mysql
- mysql_host="localhost"
- mysql_port="3306"
- mysql_username="root"
- mysql_password="dongnan"
- #
- $mysql -u${mysql_username} -p${mysql_password} -e "show full processlist;" >/tmp/processlist.txt
- $mysql -u${mysql_username} -p${mysql_password} -e "show slave status\G;" >/tmp/rep.txt
- iostat=`awk '/Slave_IO_Running/ {print $2}' /tmp/rep.txt`
- sqlstat=`awk '/Slave_SQL_Running/ {print $2}' /tmp/rep.txt`
- if [ "$iostat" = "Yes" ] && [ "$sqlstat" = "Yes" ];then
- /bin/echo -e "HTTP/1.1 200 OK\r\n"
- else
- /bin/echo -e "HTTP/1.1 503 Service Unavailable\r\n"
- fi
2.2 配置 xinetd
//定義服務,服務名必定要在 /etc/services列出ios
- tail -n1 /etc/services
mysql_rep_check 9120/tcp
//定義 super daemon 算法
- cat >> /etc/xinetd.d/mysql_rep_check << EOF
- # default: off
- #
- service mysql_rep_check
- {
- flags = REUSE
- socket_type = stream
- wait = no
- user = nobody
- server = /usr/local/bin/mysqlrep_status.sh
- log_on_failure += USERID
- disable = no
- }
- EOF
2.3 重啓xinetd sql
- /etc/init.d/xinetd restart
2.4 xinetd 日誌bash
- tail -n1 /var/log/messages
Nov 8 16:44:27 one xinetd[12224]: Started working: 1 available service
2.5 查看自定義服務端口服務器
- lsof -i :9120
COMMAND PID USER FD TYPE DEVICE SIZE NODE NAME
xinetd 12224 root 5u IPv4 1078320 TCP *:mysql_rep_check (LISTEN)
2.6 測試app
- telnet 127.0.0.1 9120
Trying 127.0.0.1...
Connected to one.test.com (127.0.0.1).
Escape character is '^]'.
HTTP/1.1 200 OK
Connection closed by foreign host.
流程
(1)應用服務器
(2)鏈接HAProxy的10.0.100.82:3306,根據算法,分配到一臺mysql slave。
(3)檢測slave的9120端口是否返回http 200狀態碼。
(4)返回200 狀態碼,HAProxy 返回正常,繼續服務。
(5)返回503,剔除該slave,並將mysql請求轉發到另一臺slave。
參考
基於Keepalived+Haproxy搭建四層負載均衡器
MySQL從庫集羣方案之HAProxy篇
更多請:
linux 相關 274134275 , 37275208(已滿)
vmware 虛擬化相關 166682360負載均衡