haproxy监测脚本实现mysql反代

haproxy监测脚本实现mysql反代

haproxy代理mysql

haproxy代理mysql的问题

​ haproxy可以在四层tcp代理mysql服务,但是要考虑2个主要问题:

  1. 后端mysql节点的健康检测;
  2. 事务的持久性;不想proxysql或mycat专用的mysql代理,haproxy不识别mysql协议,如何将一个事务内的所有sql路由到一个节点;

mysql健康检查

连通性检查

​ haproxy代理mysql时,支持mysql-check指令,该指令可以简单检查后端mysql的连通性;语法如下:

option mysql-check [user <username> [post-41] ]

集群状态检查

​ mysql-check指令只能简单的检查mysql实例的连通性,对于更复杂一些的状态监测,如主从复制状态、集群状态、某库是否存在,从节点是否只读等,需要靠自定义脚本实现监测;

​ 脚本实现监测的步骤:

  1. 用自定义脚本监测需要的mysql指标;
  2. 将脚本监测后的结果,转为http状态码供haproxy理解,(因haproxy原生支持http协议)
  3. 健康用200,不健康用503
  4. haproxy根据状态码,判断后端mysql健康与否;

mysql监测脚本示例

1、编写mysql监测脚本

[root@host3 ~]# cat /usr/bin/mysqlchk.sh 
#!/bin/bash

host=localhost
port=3306
user=root
passwd=wang
db=mysql

/usr/bin/mysql -u$user -p$passwd -h$host -e 'show databases' 2>/dev/null |grep $db

if [ $? -eq 0 ];then
	echo -en "HTTP/1.1 200 OK\r\n"
	echo -en "Content-Type: Content-Type: text/plain\r\n"
	echo -en "Connection: close\r\n"
	echo -en "\r\n"
	echo -en "Mysql is running and $db is exists.\r\n"
	echo -en "\r\n"
	sleep 0.5
	exit 0
else
	echo -en "HTTP/1.1 503 Service Unavailabel\r\n"
	echo -en "Content-Type: Content-Type: text/plain\r\n"
	echo -en "Connection: close\r\n"
	echo -en "\r\n"
	echo -en "Mysql is down or $db is not exists.\r\n"
	echo -en "\r\n"
	sleep 0.5
	exit 1

fi

2、将监测脚本加入xinted管理

# 安装xinetd包;
[root@host3 ~]# yum install -y 
xinetd

# 将mysqlchk.sh脚本,定义为xinetd管理的服务,端口为9200
[root@host3 ~]# cat /etc/xinetd.d/mysqlchk 
service mysqlchk
{
	disable = no
	flags	=	REUSE
	socket_type	=	stream
	type	=	UNLISTED
	port	=	9200
	wait	=	no
	user	=	nobody
	server	=	/usr/bin/mysqlchk.sh
	log_on_failuser	+=	USERID
	only_from	=	0.0.0.0/0
	per_source	=	UNLIMITED
}

# 添加服务和端口映射到/etc/service文件;
[root@host3 ~]# cat /etc/services |grep chk
mysqlchk	9200/tcp	#myqlchk
[root@host3 ~]# 


# 启动xinetd
[root@host3 ~]# service xinetd start
Redirecting to /bin/systemctl start xinetd.service
[root@host3 ~]# chkconfig --list
...

xinetd based services:
	chargen-dgram: 	off

	mysqlchk:      	on
	tcpmux-server: 	off
	time-dgram:    	off
	time-stream:   	off

3、脚本测试;可以根据mysql状态,输出对应的http状态码,

[root@host3 ~]# mysqlchk.sh 
HTTP/1.1 503 Service Unavailabel
Content-Type: Content-Type: text/plain
Connection: close

Mysql is down or mysql is not exists.

[root@host3 ~]# systemctl start mariadb
[root@host3 ~]# mysqlchk.sh 
mysql
HTTP/1.1 200 OK
Content-Type: Content-Type: text/plain
Connection: close

Mysql is running and mysql is exists.

4、配置haproxy代理mysql

listen mysql 0.0.0.0:3306
        mode tcp
        balance roundrobin
        option httpchk
        server db1 192.168.80.102:3306  check port 9200 inter 12000 rise 3 fall 3

# 代理的是四层3306;
# 监测用的是httpchk,探测的是9200端口,用一层转换,实现了间接mysql的探测;
# 相同思路,haproxy可以监测其他四层服务,通过自定义脚本;

reference

https://www.cnblogs.com/f-ck-need-u/p/9370579.html#11-%E5%81%A5%E5%BA%B7%E6%A3%80%E6%9F%A5%E9%97%AE%E9%A2%98

https://groups.google.com/g/codership-team/c/RO5ZyLnEWKo

updatedupdated2020-10-232020-10-23
加载评论