Haproxy 四层负载均衡
拓扑:
app ----> mysql_master(
write)
|
haproxy(
read)
|
mysql_slave*N
一 Haproxy 部分 1 haproxy 代码 - 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 - 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列出
- 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 - /etc/init.d/xinetd restart
2.4 xinetd 日志 - 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 测试 - 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。
参考 更多请:
linux 相关 274134275 , 37275208
(已满) vmware 虚拟化相关 166682360
本文转自 dongnan 51CTO博客,原文链接:http://blog.51cto.com/dngood/1120487