搜索
首页数据库mysql教程使用HAProxy给MySQL slave群进行负载均衡和状态监控

一.安装haproxy haproxy机器 http://haproxy.1wt.deu 需翻墙 tar zxvf haproxy-1.4.25.tar.gzcd haproxy-1.4.25make TARGET=linux26make installmkdir -p /usr/local/haproxy/chown nobody:nobody /usr/local/haproxy/mkdir /etc/haproxy/cp examples/haprox

blog_haproxy

一.安装haproxy

haproxy机器

http://haproxy.1wt.deu

需翻墙

tar zxvf haproxy-1.4.25.tar.gz
cd haproxy-1.4.25
make TARGET=linux26
make install
mkdir -p /usr/local/haproxy/
chown nobody:nobody /usr/local/haproxy/
mkdir /etc/haproxy/
cp examples/haproxy.cfg /etc/haproxy/
cp examples/haproxy.init /etc/init.d/haproxy
chown root:root /etc/init.d/haproxy 
chmod 700 /etc/init.d/haproxy

修改haproxy启动脚本

/usr/sbin/$BASENAME
改成
/usr/local/sbin/$BASENAME

sed -i -r 's|/usr/sbin|/usr/local/sbin|' /etc/init.d/haproxy

编辑配置文件
vi /etc/haproxy/haproxy.cfg

global
	#log 127.0.0.1	local0
	log 127.0.0.1	local3 info
	#log loghost	local0 info
	maxconn 4096
	chroot /usr/local/haproxy
	uid nobody
	gid nobody
	daemon
	debug
	#quiet
defaults
	log	global
	mode	tcp
	#option	httplog
	option	dontlognull
	retries	3
	option redispatch
	maxconn	2000
	contimeout	5000
	clitimeout	50000
	srvtimeout	50000
frontend mysql
	bind 192.168.0.107:3306
	maxconn 3000
	default_backend mysql_slave
backend	mysql_slave  
	#cookie	SERVERID rewrite
	mode tcp
	balance	roundrobin 
	#balance	source 
	#balance	leastconn 
	contimeout 10s
	timeout check 2s
	option httpchk OPTIONS * HTTP/1.1\r\nHost:\ www
	server	mysql_192_168_0_104_3306 192.168.0.104:3306 weight 1 check port 9300 inter 5s rise 2 fall 3
	server	mysql_192_168_0_104_3307 192.168.0.104:3307 weight 1 check port 9301 inter 5s rise 2 fall 3
	#server	mysql_192_168_0_106_3306 192.168.0.106:3306 weight 1 check port 9300 inter 5s rise 2 fall 3
listen  admin_status
	mode  http
	bind 192.168.0.107:8000
	option httplog
	log global
	stats enable
	stats refresh 30s
	stats hide-version
	stats realm Haproxy\ Statistics
	stats uri  /admin-status 
	stats auth  admin:123456 
	stats admin if TRUE

打开监控的iptables

iptables -A INPUT -p tcp -m tcp -s 192.168.0.0/24 --dport 8000 -j ACCEPT

添加自启动并启动haproxy服务

chkconfig –add haproxy 
chkconfig haproxy on
service haproxy start

被监控机上

我这里是单机双实例,所以有2个脚本,单机只需一个脚本和一个服务端口就行
编辑mysql检测3306脚本
vi /opt/shell/mysqlchk_status_3306.sh

#!/bin/bash 
# 
# /usr/local/bin/mysqlchk_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_HOST="localhost"
MYSQL_PORT="3306"
MYSQL_USERNAME="mysqlcheck"
MYSQL_PASSWORD="paSSword"
MYSQL_PATH="/opt/mysql/bin/"
# 
# We perform a simple query that should return a few results 
#${MYSQL_PATH}mysql -h${MYSQL_HOST} -P${MYSQL_PORT} -u${MYSQL_USERNAME} -p${MYSQL_PASSWORD} -e "show slave status\G;" >/tmp/rep${MYSQL_PORT}.txt
${MYSQL_PATH}mysql -h${MYSQL_HOST} -P${MYSQL_PORT} -u${MYSQL_USERNAME} -p${MYSQL_PASSWORD} -e "show full processlist;" >/tmp/processlist${MYSQL_PORT}.txt
${MYSQL_PATH}mysql -h${MYSQL_HOST} -P${MYSQL_PORT} -u${MYSQL_USERNAME} -p${MYSQL_PASSWORD} -e "show slave status\G;" >/tmp/rep${MYSQL_PORT}.txt
iostat=`grep "Slave_IO_Running" /tmp/rep${MYSQL_PORT}.txt  |awk '{print $2}'`            
sqlstat=`grep "Slave_SQL_Running" /tmp/rep${MYSQL_PORT}.txt |awk '{print $2}'`           
result=$(cat /tmp/processlist${MYSQL_PORT}.txt|wc -l)
echo iostat:$iostat and sqlstat:$sqlstat 
# if slave_IO_Running and Slave_sql_Running ok,then return 200 code 
if [ "$result" -gt "3" ] && [ "$iostat" = "Yes" ] && [ "$sqlstat" = "Yes" ];
then
        # mysql is fine, return http 200 
        /bin/echo -e "HTTP/1.1 200 OK\r\n" 
else
        # mysql is down, return http 503 
        /bin/echo -e "HTTP/1.1 503 Service Unavailable\r\n" 
fi

vi /opt/shell/mysqlchk_status_3307.sh

#!/bin/bash 
# 
# /usr/local/bin/mysqlchk_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_HOST="localhost"
MYSQL_PORT="3307"
MYSQL_USERNAME="mysqlcheck"
MYSQL_PASSWORD="paSSword"
MYSQL_PATH="/opt/mysql/bin/"
# 
# We perform a simple query that should return a few results 
#${MYSQL_PATH}mysql -h${MYSQL_HOST} -P${MYSQL_PORT} -u${MYSQL_USERNAME} -p${MYSQL_PASSWORD} -e "show slave status\G;" >/tmp/rep${MYSQL_PORT}.txt
${MYSQL_PATH}mysql -S/data/mysql/mysql.sock -u${MYSQL_USERNAME} -p${MYSQL_PASSWORD} -e "show full processlist;" >/tmp/processlist${MYSQL_PORT}.txt
${MYSQL_PATH}mysql -S/data/mysql/mysql.sock -u${MYSQL_USERNAME} -p${MYSQL_PASSWORD} -e "show slave status\G;" >/tmp/rep${MYSQL_PORT}.txt
iostat=`grep "Slave_IO_Running" /tmp/rep${MYSQL_PORT}.txt  |awk '{print $2}'`            
sqlstat=`grep "Slave_SQL_Running" /tmp/rep${MYSQL_PORT}.txt |awk '{print $2}'`           
result=$(cat /tmp/processlist${MYSQL_PORT}.txt|wc -l)
#echo iostat:$iostat and sqlstat:$sqlstat 
echo $result
# if slave_IO_Running and Slave_sql_Running ok,then return 200 code 
if [ "$result" -gt "3" ] && [ "$iostat" = "Yes" ] && [ "$sqlstat" = "Yes" ];
then
        # mysql is fine, return http 200 
        /bin/echo -e "HTTP/1.1 200 OK\r\n" 
else
        # mysql is down, return http 503 
        /bin/echo -e "HTTP/1.1 503 Service Unavailable\r\n" 
fi

chmod 775 /opt/shell/mysqlchk_status_3306.sh
chmod 775 /opt/shell/mysqlchk_status_3307.sh

在mysql slave另行建立一个具有process和slave_client权限的账号。

CREATE USER 'mysqlcheck'@'localhost' IDENTIFIED BY 'PaSSword';
GRANT PROCESS , REPLICATION CLIENT ON * . * TO 'mysqlcheck'@'localhost' IDENTIFIED BY 'PaSSword' WITH MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0 ;
flush privileges;

测试脚本
./mysqlchk_status_3306.sh

添加服务
绑定内网ip,运行于930端口,只开放给192.168.0内网
yum install -y xinetd
vim /etc/xinetd.d/mysql_status

service mysqlchk_status3306
{ 
        flags           = REUSE 
        socket_type     = stream 
        bind            = 192.168.0.104
        port            = 9300
        wait            = no 
        user            = nobody 
        server          = /opt/shell/mysqlchk_status_3306.sh
        log_type        = FILE /dev/null
        log_on_failure  += USERID 
        disable         = no 
        only_from       = 192.168.0.0/24 
}
service mysqlchk_status3307
{ 
        flags           = REUSE 
        socket_type     = stream 
        bind            = 192.168.0.104
        port            = 9301
        wait            = no 
        user            = nobody 
        server          = /opt/shell/mysqlchk_status_3307.sh
        log_type        = FILE /dev/null
        log_on_failure  += USERID 
        disable         = no 
        only_from       = 192.168.0.0/24 
}

bind和only_from的ip地址要有haproxy能请求的权限,使用drbd用0.0.0.0
user要用server脚本的执行权限
port端口要在/etc/service 中声明

chattr -i /etc/services
vi /etc/services

mysqlchk_status3306    9300/tcp			#haproxy mysql check
mysqlchk_status3307    9301/tcp			#haproxy mysql check

services中的mysqlchk_status3306 要和xinetd.d中service名对应

打开iptables

iptables -A INPUT -p tcp -m tcp -s 192.168.0.0/24 --dport 9300 -j ACCEPT
iptables -A INPUT -p tcp -m tcp -s 192.168.0.0/24 --dport 9301 -j ACCEPT

/etc/init.d/iptables save

添加自启动及启动服务
chkconfig xinetd –level 345 on
/etc/init.d/xinetd start

查看是否运行
netstat -lntp

Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address               Foreign Address             State       PID/Program name   
tcp        0      0 0.0.0.0:9300                0.0.0.0:*                   LISTEN      4863/xinetd         
tcp        0      0 0.0.0.0:9301                0.0.0.0:*                   LISTEN      4863/xinetd

如果没有的话注意检测下bind地址及服务端口

在监控机运行测试
telnet 192.168.0.104 9300

Trying 192.168.0.104...
Connected to 192.168.0.104 (192.168.0.104).
Escape character is '^]'.
/opt/shell/mysqlchk_status_3306.sh: line 24: /tmp/processlist3306.txt: Permission denied
/opt/shell/mysqlchk_status_3306.sh: line 25: /tmp/rep3306.txt: Permission denied
HTTP/1.1 200 OK
Connection closed by foreign host.

之前用root运行过所以报错,在被监控机删除临时文件

rm -f /tmp/processlist3306.txt /tmp/processlist3307.txt
rm -f /tmp/rep3306.txt /tmp/rep3307.txt

没有输出则需检查mysqlchk_status_3306.sh脚本执行权限

启动后/var/log/messages 中会有很多日志

Oct 23 14:37:00 lova xinetd[11057]: START: mysqlchk_status3306 pid=11464 from=192.168.0.22
Oct 23 14:37:00 lova xinetd[11057]: EXIT: mysqlchk_status3306 status=0 pid=11464 duration=0(sec)
Oct 23 14:37:05 lova xinetd[11057]: START: mysqlchk_status3306 pid=11494 from=192.168.0.22
Oct 23 14:37:05 lova xinetd[11057]: EXIT: mysqlchk_status3306 status=0 pid=11494 duration=0(sec)

在haproxy配置中将日志输出到黑洞
log_type = FILE /dev/null

查看监控

直接访问localhost是503

http://localhost/

503 Service Unavailable

No server is available to handle this request.

加上admin-status

http://localhost/admin-status

应用时需在slave mysql上的mysql添加通过haproxy的用户权限

haproxy的命令
/etc/init.d/haproxy
Usage: haproxy {start|stop|restart|reload|condrestart|status|check}


优化time_wait,防止端口耗尽
vi /etc/sysctl.conf

net.ipv4.ip_local_port_range = 1025 65000
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_tw_recycle = 1
net.ipv4.tcp_fin_timeout = 15
net.ipv4.tcp_max_tw_buckets = 35000

sysctl -p

使用nginx反向代理haprox后台

#省略
listen  admin_status
    mode  http
    bind 192.168.0.107:8000
    option httplog
    log global
    stats enable
    stats refresh 30s
    stats hide-version
    stats realm Haproxy\ Statistics
    #stats uri  /admin-status
    stats uri  /haproxy/
    #stats auth  admin:123456
    #stats admin if TRUE

nginx.conf

#省略
             location ~* ^/haproxy/
             {
		  proxy_pass		http://192.168.0.107:8000;
		  proxy_set_header	Host		$host;
		  proxy_set_header	X-Real-IP	$remote_addr;
		  proxy_set_header	X-Forwarded-For	$proxy_add_x_forwarded_for;
		  #proxy_set_header	X-Forwarded-For	$remote_addr;
		  proxy_redirect	off;
             }
#省略

参考:

http://linux.die.net/man/5/xinetd.conf

http://adslroot.blogspot.com/2013/12/haproxy-mysql.html

http://sssslide.com/www.slideshare.net/Severalnines/haproxy-mysql-slides

 


声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
MySQL中的存储过程是什么?MySQL中的存储过程是什么?May 01, 2025 am 12:27 AM

存储过程是MySQL中的预编译SQL语句集合,用于提高性能和简化复杂操作。1.提高性能:首次编译后,后续调用无需重新编译。2.提高安全性:通过权限控制限制数据表访问。3.简化复杂操作:将多条SQL语句组合,简化应用层逻辑。

查询缓存如何在MySQL中工作?查询缓存如何在MySQL中工作?May 01, 2025 am 12:26 AM

MySQL查询缓存的工作原理是通过存储SELECT查询的结果,当相同查询再次执行时,直接返回缓存结果。1)查询缓存提高数据库读取性能,通过哈希值查找缓存结果。2)配置简单,在MySQL配置文件中设置query_cache_type和query_cache_size。3)使用SQL_NO_CACHE关键字可以禁用特定查询的缓存。4)在高频更新环境中,查询缓存可能导致性能瓶颈,需通过监控和调整参数优化使用。

与其他关系数据库相比,使用MySQL的优点是什么?与其他关系数据库相比,使用MySQL的优点是什么?May 01, 2025 am 12:18 AM

MySQL被广泛应用于各种项目中的原因包括:1.高性能与可扩展性,支持多种存储引擎;2.易于使用和维护,配置简单且工具丰富;3.丰富的生态系统,吸引大量社区和第三方工具支持;4.跨平台支持,适用于多种操作系统。

您如何处理MySQL中的数据库升级?您如何处理MySQL中的数据库升级?Apr 30, 2025 am 12:28 AM

MySQL数据库升级的步骤包括:1.备份数据库,2.停止当前MySQL服务,3.安装新版本MySQL,4.启动新版本MySQL服务,5.恢复数据库。升级过程需注意兼容性问题,并可使用高级工具如PerconaToolkit进行测试和优化。

您可以使用MySQL的不同备份策略是什么?您可以使用MySQL的不同备份策略是什么?Apr 30, 2025 am 12:28 AM

MySQL备份策略包括逻辑备份、物理备份、增量备份、基于复制的备份和云备份。1.逻辑备份使用mysqldump导出数据库结构和数据,适合小型数据库和版本迁移。2.物理备份通过复制数据文件,速度快且全面,但需数据库一致性。3.增量备份利用二进制日志记录变化,适用于大型数据库。4.基于复制的备份通过从服务器备份,减少对生产系统的影响。5.云备份如AmazonRDS提供自动化解决方案,但成本和控制需考虑。选择策略时应考虑数据库大小、停机容忍度、恢复时间和恢复点目标。

什么是mySQL聚类?什么是mySQL聚类?Apr 30, 2025 am 12:28 AM

MySQLclusteringenhancesdatabaserobustnessandscalabilitybydistributingdataacrossmultiplenodes.ItusestheNDBenginefordatareplicationandfaulttolerance,ensuringhighavailability.Setupinvolvesconfiguringmanagement,data,andSQLnodes,withcarefulmonitoringandpe

如何优化数据库架构设计以在MySQL中的性能?如何优化数据库架构设计以在MySQL中的性能?Apr 30, 2025 am 12:27 AM

在MySQL中优化数据库模式设计可通过以下步骤提升性能:1.索引优化:在常用查询列上创建索引,平衡查询和插入更新的开销。2.表结构优化:通过规范化或反规范化减少数据冗余,提高访问效率。3.数据类型选择:使用合适的数据类型,如INT替代VARCHAR,减少存储空间。4.分区和分表:对于大数据量,使用分区和分表分散数据,提升查询和维护效率。

您如何优化MySQL性能?您如何优化MySQL性能?Apr 30, 2025 am 12:26 AM

tooptimizemysqlperformance,lofterTheSeSteps:1)inasemproperIndexingTospeedUpqueries,2)使用ExplaintplaintoAnalyzeandoptimizequeryPerformance,3)ActiveServerConfigurationStersLikeTlikeTlikeTlikeIkeLikeIkeIkeLikeIkeLikeIkeLikeIkeLikeNodb_buffer_pool_sizizeandmax_connections,4)

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

WebStorm Mac版

WebStorm Mac版

好用的JavaScript开发工具

SublimeText3 英文版

SublimeText3 英文版

推荐:为Win版本,支持代码提示!

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器