千家信息网

怎么用MySQL+Keepalived+haproxy实现负载均衡

发表于:2024-11-23 作者:千家信息网编辑
千家信息网最后更新 2024年11月23日,本篇内容主要讲解"怎么用MySQL+Keepalived+haproxy实现负载均衡",感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习"怎么用MySQL+Kee
千家信息网最后更新 2024年11月23日怎么用MySQL+Keepalived+haproxy实现负载均衡

本篇内容主要讲解"怎么用MySQL+Keepalived+haproxy实现负载均衡",感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习"怎么用MySQL+Keepalived+haproxy实现负载均衡"吧!

数据库环境:

slave2:192.168.8.59

slave3:192.168.8.61

工具包:

keepalived-1.4.5.tar.gz

haproxy-1.8.9.tar.gz

此次实验中,slave2和slave3利用 keepalived和haproxy实现负载均衡,本文着重讲解负载均衡的搭建过程。

一、修改内核参数

echo "net.ipv4.ip_nonlocal_bind=1" >> /etc/sysctl.confecho "net.ipv4.ip_forward=1" >> /etc/sysctl.confsysctl -p

net.ipv4.ip_nonlocal_bind=1 意思是启动haproxy的时候,允许忽视VIP的存在

net.ipv4.ip_forward = 1 haproxy代理服务器同时也要打开内核的转发功能

二、安装keepalived和haproxy

mount /dev/cdrom /mediayum install kernel-devel openssl-devel popt-devel -ycd /softwaretar zxvf keepalived-1.4.5.tar.gzcd keepalived-1.4.5./configure --prefix=/usr/local/keepalived/make && make installsystemctl enable keepalived

vi /usr/local/keepalived/etc/sysconfig/keepalived

KEEPALIVED_OPTIONS="-D -d -S 0"

vi /etc/rsyslog.conf

local0.* /var/log/keepalived.log
systemctl restart rsyslog
cd /softwaretar zxvf haproxy-1.8.9.tar.gzcd haproxy-1.8.9make TARGET=linux2628 PREFIX=/usr/local/haproxymake install PREFIX=/usr/local/haproxy/usr/local/haproxy/sbin/haproxy -vuseradd -r -s /sbin/nologin haproxytouch /var/log/haproxy.logchmod 755 /var/log/haproxy.log

修改日志位置

vi /etc/rsyslog.conflocal0.* /var/log/haproxy.logvi /etc/sysconfig/rsyslogSYSLOGD_OPTIONS="-r -m 0 -c 2"systemctl restart rsyslog

三、配置keepalived

192.168.8.59

/etc/keepalived/keepalived.conf

! Configuration File for keepalivedglobal_defs {router_id mysql-slavenotification_email {zdd5503@163.com}notification_email_from zdd5503@163.comsmtp_server stmp.163.comsmtp_connect_timeout 30}vrrp_script chk_haproxy {script "/etc/keepalived/scripts/check_haproxy.sh"interval 2weight 2}vrrp_instance v_mysql_slave_zdd01 {interface enp0s3state MASTERvirtual_router_id 98priority 200nopreemptvirtual_ipaddress {192.168.8.98/24}track_script {chk_haproxy}notify_master /etc/keepalived/scripts/haproxy_master.shnotify_backup /etc/keepalived/scripts/haproxy_backup.shnotify_fault /etc/keepalived/scripts/haproxy_fault.shnotify_stop /etc/keepalived/scripts/haproxy_stop.sh}

192.168.8.61

/etc/keepalived/keepalived.conf

! Configuration File for keepalivedglobal_defs {router_id mysql-slavenotification_email {zdd5503@163.com}notification_email_from zdd5503@163.comsmtp_server stmp.163.comsmtp_connect_timeout 30}vrrp_script chk_haproxy {script "/etc/keepalived/scripts/check_haproxy.sh"interval 2weight 2}vrrp_instance v_mysql_slave_zdd01 {interface enp0s3state BACKUPvirtual_router_id 98priority 150nopreemptvirtual_ipaddress {192.168.8.98/24}track_script {chk_haproxy}notify_master /etc/keepalived/scripts/haproxy_master.shnotify_backup /etc/keepalived/scripts/haproxy_backup.shnotify_fault /etc/keepalived/scripts/haproxy_fault.shnotify_stop /etc/keepalived/scripts/haproxy_stop.sh}

四、配置haproxy

192.168.8.59和192.168.8.61都做如下脚本配置:

mkdir -p /etc/keepalived/scripts

vi /etc/keepalived/scripts/check_haproxy.sh

#!/bin/bashSTARTHAPROXY="/usr/local/haproxy/sbin/haproxy -f /usr/local/haproxy/haproxy.cfg"#STOPKEEPALIVED="systemctl stop keepalived"LOGFILE="/etc/keepalived/scripts/keepalived-haproxy-state.log"echo "[check_haproxy status]" >> $LOGFILEA=`ps -C haproxy --no-header |wc -l`echo "[check_haproxy status]" >> $LOGFILEdate >> $LOGFILEif [ $A -eq 0 ];thenecho $STARTHAPROXY >> $LOGFILE$STARTHAPROXY >> $LOGFILE 2>&1sleep 5fiif [ `ps -C haproxy --no-header |wc -l` -eq 0 ];thenexit 0elseexit 1fi

vi /etc/keepalived/scripts/haproxy_master.sh

#!/bin/bashSTARTHAPROXY=`/usr/local/haproxy/sbin/haproxy -f /usr/local/haproxy/haproxy.cfg`STOPHAPROXY=`ps -ef |grep sbin/haproxy| grep -v grep|awk '{print $2}'|xargs kill -s 9`LOGFILE="/etc/keepalived/scripts/keepalived-haproxy-state.log"echo "[master]" >> $LOGFILEdate >> $LOGFILEecho "Being master...." >> $LOGFILE 2>&1echo "stop haproxy...." >> $LOGFILE 2>&1$STOPHAPROXY >> $LOGFILE 2>&1echo "start haproxy...." >> $LOGFILE 2>&1$STARTHAPROXY >> $LOGFILE 2>&1echo "haproxy stared ..." >> $LOGFILE

vi /etc/keepalived/scripts/haproxy_backup.sh

#!/bin/bashSTARTHAPROXY=`/usr/local/haproxy/sbin/haproxy -f /usr/local/haproxy/haproxy.cfg`STOPHAPROXY=`ps -ef |grep sbin/haproxy| grep -v grep|awk '{print $2}'|xargskill -s 9`LOGFILE="/etc/keepalived/scripts/keepalived-haproxy-state.log"echo "[master]" >> $LOGFILEdate >> $LOGFILEecho "Being master...." >> $LOGFILE 2>&1echo "stop haproxy...." >> $LOGFILE 2>&1$STOPHAPROXY >> $LOGFILE 2>&1echo "start haproxy...." >> $LOGFILE 2>&1$STARTHAPROXY >> $LOGFILE 2>&1echo "haproxy stared ..." >> $LOGFILE

vi /etc/keepalived/scripts/haproxy_fault.sh

#!/bin/bashLOGFILE=/etc/keepalived/scripts/keepalived-haproxy-state.logecho "[fault]" >> $LOGFILEdate >> $LOGFILE

vi /etc/keepalived/scripts/haproxy_stop.sh

#!/bin/bashLOGFILE=/etc/keepalived/scripts/keepalived-haproxy-state.logecho "[stop]" >> $LOGFILEdate >> $LOGFILE

更改脚本属性

chmod 755 /etc/keepalived/scripts/*

配置haproxy

192.168.8.59

vi /usr/local/haproxy/haproxy.cfg

global   #全局配置参数                log 127.0.0.1 local0 notice #日志                #user haproxy                 #group haproxy        daemon  #以后台形式运行haproxy        #quiet        nbproc 1  #  进程数量,可以设置多个进程提高性能        pidfile /usr/local/haproxy/haproxy.pid   #haproxy的pid存放路径                  defaults   #一些默认参数                log global  #全局日志                retries 3  # 3次连接失败就认为服务器不可用                option dontlognull  # 保存haproxy不记录上次负载均衡发送过来的用于检测状态没有数据的心跳包                option redispatch # 对应的服务器挂掉后,强制指向到其它正常的服务器                maxconn 2000  #默认最大连接数                timeout queue 1m # 等待最大时长                timeout http-request 10s #客户端建立连接又不请求数据的时候超过10S,就关闭客户端连接                timeout connect 10s # 定义haproxy将客户端请求转发至后端服务器所等待的超时时长                 timeout server 1m # 服务端非活动状态的超时时长                timeout client 1m  # 客户端非活动状态的超时时长                timeout http-keep-alive 10s #   设置http-keep-alive超时时长                timeout check 10s #健康状态监测时的超时时间                balance roundrobin #负载均衡方式,轮询方式(保持会话session:源地址/cookies,针对web应用服务器) #定义负载均衡的配置       listen mysql_slave_wgpt_lb1        bind 192.168.8.98:3307 #绑定的IP与端口 (建议bind *:3306)        mode tcp #模式是TCP,(7层http,4层tcp,如果是mysql用tcp,如果是weblogic/was/tomcat之类的就用http)                option mysql-check user haproxy_check #通过mysql连接去检测mysql是否可以访问                stats hide-version #隐藏统计页上的haproxy的版本信息                balance roundrobin #负载均衡方式,轮询方式                server slave2 192.168.8.59:3306 weight 1 check inter 2000 rise 2 fall 5 maxconn 300                server slave3 192.168.8.61:3306 weight 1 check inter 2000 rise 2 fall 5 maxconn 300                #服务器定义,check inter 2000检测心跳频率,rise 2 2次正确认为服务器可用,fall 5 5次失败认为服务器不可用,                #maxconn 300 最大连接数300#自带的监控服务器的配置listen  haproxy_stats         mode http         bind *:8888         option httplog         stats refresh 5s              stats uri /haproxy-stat         stats realm www.zdd.com monitor        stats realm Haproxy Manager         stats auth haproxy:haproxy

192.168.8.61

vi /usr/local/haproxy/haproxy.cfg

global   #全局配置参数                log 127.0.0.1 local0 notice #日志                #user haproxy                 #group haproxy        daemon  #以后台形式运行haproxy        #quiet        nbproc 1  #  进程数量,可以设置多个进程提高性能        pidfile /usr/local/haproxy/haproxy.pid   #haproxy的pid存放路径                  defaults   #一些默认参数                log global  #全局日志                retries 3  # 3次连接失败就认为服务器不可用                option dontlognull  # 保存haproxy不记录上次负载均衡发送过来的用于检测状态没有数据的心跳包                option redispatch # 对应的服务器挂掉后,强制指向到其它正常的服务器                maxconn 2000  #默认最大连接数                timeout queue 1m # 等待最大时长                timeout http-request 10s #客户端建立连接又不请求数据的时候超过10S,就关闭客户端连接                timeout connect 10s # 定义haproxy将客户端请求转发至后端服务器所等待的超时时长                 timeout server 1m # 服务端非活动状态的超时时长                timeout client 1m  # 客户端非活动状态的超时时长                timeout http-keep-alive 10s #   设置http-keep-alive超时时长                timeout check 10s #健康状态监测时的超时时间                balance roundrobin #负载均衡方式,轮询方式(保持会话session:源地址/cookies,针对web应用服务器) #定义负载均衡的配置       listen mysql_slave_wgpt_lb1        bind 192.168.8.98:3307 #绑定的IP与端口 (建议bind *:3306)        mode tcp #模式是TCP,(7层http,4层tcp,如果是mysql用tcp,如果是weblogic/was/tomcat之类的就用http)                option mysql-check user haproxy_check #通过mysql连接去检测mysql是否可以访问                stats hide-version #隐藏统计页上的haproxy的版本信息                balance roundrobin #负载均衡方式,轮询方式                server slave2 192.168.8.59:3306 weight 1 check inter 2000 rise 2 fall 5 maxconn 300                server slave3 192.168.8.61:3306 weight 1 check inter 2000 rise 2 fall 5 maxconn 300                #服务器定义,check inter 2000检测心跳频率,rise 2 2次正确认为服务器可用,fall 5 5次失败认为服务器不可用,                #maxconn 300 最大连接数300#自带的监控服务器的配置listen  haproxy_stats         mode http         bind *:8888         option httplog         stats refresh 5s              stats uri /haproxy-stat         stats realm www.zdd.com monitor        stats realm Haproxy Manager         stats auth haproxy:haproxy

五、添加 haproxy_check 用户

drop user haproxy_check@'%';create user haproxy_check@'192.168.8.59';create user haproxy_check@'192.168.8.61';create user haproxy_check@'192.168.8.98';grant usage on *.* to haproxy_check@'192.168.8.59';grant usage on *.* to haproxy_check@'192.168.8.61';grant usage on *.* to haproxy_check@'192.168.8.98';
mysql> select user,host from mysql.user;+---------------+--------------+| user          | host         |+---------------+--------------+| repl          | 192.168.8.%  || root          | 192.168.8.%  || haproxy_check | 192.168.8.59 || haproxy_check | 192.168.8.61 || haproxy_check | 192.168.8.98 || mysql.session | localhost    || mysql.sys     | localhost    || root          | localhost    |+---------------+--------------+

六、启动 keepalived

systemctl daemon-reloadsystemctl enable keepalivedsystemctl start keepalived
ip a |grep 98ps -ef |grep keepalived

七、配置keepalived监控脚本

两个节点都做如下配置:

vi /etc/keepalived/keepcheck.sh

#!/bin/bashwhile :dokeepalivedcheck=`ps -C keepalived --no-header | wc -l`if [ $keepalivedcheck -eq 0 ];thensystemctl start keepalivedelseecho "keepalived is running"fisleep 5done
chmod +x /etc/keepalived/keepcheck.shnohup /etc/keepalived/keepcheck.sh &echo "nohup /etc/keepalived/keepcheck.sh &" >> /etc/rc.d/rc.local

八、配置haproxy 启动脚本

vim /etc/rc.d/init.d/haproxy

#! /bin/shset -ePATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/haproxy/sbinPROGDIR=/usr/local/haproxyPROGNAME=haproxyDAEMON=$PROGDIR/sbin/$PROGNAMECONFIG=$PROGDIR/$PROGNAME.cfgPIDFILE=$PROGDIR/$PROGNAME.pidDESC="HAProxy daemon"SCRIPTNAME=/etc/init.d/$PROGNAME# Gracefully exit if the package has been removed.test -x $DAEMON || exit 0start(){echo -n "Starting $DESC: $PROGNAME"$DAEMON -f $CONFIGecho "."}stop(){echo -n "Stopping $DESC: $PROGNAME"haproxy_pid=`cat $PIDFILE`kill -9 $haproxy_pidecho "."}restart(){echo -n "Restarting $DESC: $PROGNAME"$DAEMON -f $CONFIG -p $PIDFILE -sf $(cat $PIDFILE)echo "."}case "$1" instart)start;;stop)stop;;restart)restart;;*)echo "Usage: $SCRIPTNAME {start|stop|restart}" >&2exit 1;;esacexit 0
chmod +x /etc/rc.d/init.d/haproxyecho "nohup /etc/rc.d/init.d/haproxy start &" >> /etc/rc.d/rc.local
systemctl stop keepalivedsystemctl start keepalivedtail -f /var/log/keepalived.log
/etc/rc.d/init.d/haproxy start/etc/rc.d/init.d/haproxy stoptail -f /var/log/haproxy.log

haproxy控制台访问地址:

http://192.168.8.98:8888/haproxy-stat

九、测试负载均衡

[root@slave3 ~]# mysql -uroot -pmysql -h292.168.8.98 -P3307 -e "show variables like 'server_id';"mysql: [Warning] Using a password on the command line interface can be insecure.+---------------+-------+| Variable_name | Value |+---------------+-------+| server_id     | 59    |+---------------+-------+[root@slave3 ~]# mysql -uroot -pmysql -h292.168.8.98 -P3307 -e "show variables like 'server_id';"mysql: [Warning] Using a password on the command line interface can be insecure.+---------------+-------+| Variable_name | Value |+---------------+-------+| server_id     | 61    |+---------------+-------+[root@slave3 ~]# mysql -uroot -pmysql -h292.168.8.98 -P3307 -e "show variables like 'server_id';"mysql: [Warning] Using a password on the command line interface can be insecure.+---------------+-------+| Variable_name | Value |+---------------+-------+| server_id     | 59    |+---------------+-------+[root@slave3 ~]# mysql -uroot -pmysql -h292.168.8.98 -P3307 -e "show variables like 'server_id';"mysql: [Warning] Using a password on the command line interface can be insecure.+---------------+-------+| Variable_name | Value |+---------------+-------+| server_id     | 61    |+---------------+-------+[root@slave3 ~]# mysql -uroot -pmysql -h292.168.8.98 -P3307 -e "show variables like 'server_id';"mysql: [Warning] Using a password on the command line interface can be insecure.+---------------+-------+| Variable_name | Value |+---------------+-------+| server_id     | 59    |+---------------+-------+[root@slave3 ~]# mysql -uroot -pmysql -h292.168.8.98 -P3307 -e "show variables like 'server_id';"mysql: [Warning] Using a password on the command line interface can be insecure.+---------------+-------+| Variable_name | Value |+---------------+-------+| server_id     | 61    |+---------------+-------+

因为我们在haproxy配置文件中配置了权重为1:1,所以会话将交替分发到两个节点上边。

到此,相信大家对"怎么用MySQL+Keepalived+haproxy实现负载均衡"有了更深的了解,不妨来实际操作一番吧!这里是网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

0