lvs + keepalived + mysql duplicação master para alcançar o compartilhamento de carga e alta disponibilidade


Keepalived + lvs + replicação master mysql é uma solução de alta disponibilidade Mysql comumente usada, onde lvs fornece balanceamento de carga de leitura e Keepalived realiza failover automático por meio de VIP virtual drift. Embora Mysql seja configurado como uma replicação master, geralmente é adotado Single-point escrever para garantir a consistência dos dados.


Insira a descrição da imagem aqui

Hospedeiro IP Recursos
VIP 192.168.30.250
guarda-mestre 192.168.30.243 lvs + keepalived (主)
manter escravo 192.168.30.244 lvs + keepalived (备)
mestre-mestre 192.168.30.245 mysql (mestre)
senhor de escravos 1929.168.30.246 mysql (mestre)

mysql dual master

A configuração do mysql dual-master e master-slave é semelhante, mas as seguintes etapas são adicionadas

[root@mysql-master ~]# vim /etc/my.cnf
[mysqld]
basedir = /usr/local/mysql
datadir = /opt/data
socket = /tmp/mysql.sock
port = 3306
pid-file = /opt/data/mysql.pid
user = mysql
skip-name-resolve
log_slave_updates = 1    ##双主需要开启log_slave_updates功能
server-id = 10           ##不能相同
log-bin = mysql_bin      ##双主两个都是log-bin
auto_increment_offset = 1   ##表示自增长字段从1开始,他的取值范围是1 .. 65535
auto_increment_increment = 2 ##表示自增长字段每次递增2,取值范围是2 .. 65535

Reinicie o serviço


Crie uma conta autorizada no host mestre e permita a conexão no host escravo (192.168.30.246)

mysql> grant replication slave on *.* to 'repl'@'192.168.30.246' identified by 'repl';
Query OK, 0 rows affected, 1 warning (0.00 sec)


Ver as informações de status do binlog atual do mestre

mysql> show master status;
+------------------+----------+--------------+------------------+-------------------+
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+------------------+----------+--------------+------------------+-------------------+
| mysql_bin.000001 |      455 |              |                  |                   |
+------------------+----------+--------------+------------------+-------------------+
1 row in set (0.00 sec)

Defina o mestre como seu próprio servidor mestre no servidor escravo e habilite a função escravo

mysql> change master to
    -> master_host = '192.168.30.245',
    -> master_user = 'repl',
    -> master_password = 'repl',
    -> master_log_file = 'mysql_bin.000001',
    -> master_log_pos = 455 ;
Query OK, 0 rows affected, 2 warnings (0.02 sec)



mysql> start slave;
Query OK, 0 rows affected (0.00 sec)



mysql> show slave status\G;
*************************** 1. row ***************************

             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes


Modifique o arquivo de configuração da biblioteca

[root@mysql-slave ~]# cat /etc/my.cnf
[mysqld]
basedir = /usr/local/mysql
datadir = /opt/data
socket = /tmp/mysql.sock
port = 3306
pid-file = /opt/data/mysql.pid
user = mysql
skip-name-resolve
log_slave_updates = 1    ##双主需要开启log_slave_updates功能
server-id = 20           ##不能相同
log-bin = mysql_bin      ##双主两个都是log-bin
auto_increment_offset = 1   ##表示自增长字段从1开始,他的取值范围是1 .. 65535
auto_increment_increment = 2 ##表示自增长字段每次递增2,取值范围是2 .. 65535


Crie uma conta autorizada no host escravo e permita a conexão no host mestre (192.168.30.246)

mysql> grant replication slave on *.* to 'repl'@'192.168.30.245' identified by 'repl';
Query OK, 0 rows affected, 1 warning (0.00 sec)


Ver as informações de status do binlog atual do escravo

mysql> show master status;
+------------------+----------+--------------+------------------+-------------------+
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+------------------+----------+--------------+------------------+-------------------+
| mysql_bin.000001 |      154 |              |                  |                   |
+------------------+----------+--------------+------------------+-------------------+
1 row in set (0.00 sec)


Defina o escravo como seu próprio servidor mestre no servidor mestre e habilite a função escravo

mysql> change master to
    -> master_host = '192.168.30.246',
    -> master_user = 'repl',
    -> master_password = 'repl',
    -> master_log_file = 'mysql_bin.000001',
    -> master_log_pos = 154 ;
Query OK, 0 rows affected, 2 warnings (0.00 sec)


mysql> show slave status\G;
*************************** 1. row ***************************
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes

manter vivo

Eu uso o yum para instalar o
principal keepalived

[root@keep-master ~]# yum -y install keepalived  ipvsadm

[root@keep-master ~]# vim /etc/keepalived/keepalived.conf 
! Configuration File for keepalived

global_defs {
   router_id lb01       
}

vrrp_instance VI_1 {
    state MASTER
    interface ens33
    virtual_router_id 20 
    priority 100
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass zyy                 
    }
    virtual_ipaddress {
        192.168.30.250                ##VIP
    }
}

virtual_server 192.168.30.250 3306 {      # 定义虚拟服务器,地址与上面的virtual_ipaddress相同
    delay_loop 3                          # 健康检查时间间隔,3秒
    lb_algo rr                            # 负载均衡调度算法:rr|wrr|lc|wlc|sh|dh|lblc
    lb_kind DR                            # 负载均衡转发规则:NAT|DR|TUN
   # persistence_timeout 5                # 会话保持时间5秒,动态服务建议开启
    protocol TCP                          # 转发协议protocol,一般有tcp和udp两种

 #后端真实服务器,有几台就设置几个
    real_server 192.168.30.245 3306 {     
        weight 1
        TCP_CHECK {
            connect_port 3306
            connect_timeout 3
            nb_get_retry 3
            delay_before_retry 3
        }
    }

    real_server 192.168.30.246 3306 {
        weight 1
        TCP_CHECK {
            connect_port 3306
            connect_timeout 3
            nb_get_retry 3
            delay_before_retry 3
        }
    }
}

O mesmo da biblioteca, altere a prioridade e defina-a sem preempção.

[root@keep-slave ~]# yum -y install keepalived  ipvsadm

[root@keep-slave ~]# vim /etc/keepalived/keepalived.conf 
! Configuration File for keepalived

global_defs {
   router_id lb02
}

vrrp_instance VI_1 {
    state BACKUP              ##BACKUP
    interface ens33
    virtual_router_id 20    
    priority 80             ##优先级要比master小
    nopreempt
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass zyy        
    }
    virtual_ipaddress {
        192.168.30.250
    }
}

virtual_server 192.168.30.250 3306 {
    delay_loop 3
    lb_algo rr
    lb_kind DR
  #  persistence_timeout 5
    protocol TCP

    real_server 192.168.30.245 3306 {
        weight 1
        TCP_CHECK {
            connect_port 3306
            connect_timeout 3
            nb_get_retry 3
            delay_before_retry 3
        }
    }

    real_server 192.168.30.246 3306 {
        weight 1
        TCP_CHECK {
            connect_port 3306
            connect_timeout 3
            nb_get_retry 3
            delay_before_retry 3
        }
    }
}


Abra o serviço keepalived

[root@keep-master ~]# systemctl start keepalived
[root@keep-slave ~]# systemctl start keepalived

Ver VIP
Insira a descrição da imagem aqui
Insira a descrição da imagem aqui

Verifique o status do cluster LVS neste momento, você pode ver que existem dois RealServers, algoritmos de agendamento, pesos e outras informações no cluster. ActiveConn representa o número de conexões ativas do RealServer atual.

[root@keep-master ~]# ipvsadm -ln
IP Virtual Server version 1.2.1 (size=4096)
Prot LocalAddress:Port Scheduler Flags
  -> RemoteAddress:Port           Forward Weight ActiveConn InActConn
TCP  192.168.30.250:3306 rr
  -> 192.168.30.245:3306          Route   1      0          0         
  -> 192.168.30.246:3306          Route   1      0          0       


Escreva o script de configuração de rede RealServer
192.168.30.245 e 192.168.30.246 escreva as mesmas coisas, aqui está uma demonstração

[root@mysql-master ~]# cat /etc/init.d/realserver 
#!/bin/bash
VIP=192.168.30.250
. /etc/rc.d/init.d/functions

case "$1" in
# 禁用本地的ARP请求、绑定本地回环地址
start)
    /sbin/ifconfig lo down
    /sbin/ifconfig lo up
    echo "1" >/proc/sys/net/ipv4/conf/lo/arp_ignore
    echo "2" >/proc/sys/net/ipv4/conf/lo/arp_announce
    echo "1" >/proc/sys/net/ipv4/conf/all/arp_ignore
    echo "2" >/proc/sys/net/ipv4/conf/all/arp_announce
    /sbin/sysctl -p >/dev/null 2>&1
    /sbin/ifconfig lo:0 $VIP netmask 255.255.255.255 up # 在回环地址上绑定VIP,设定掩码,与Direct Server上自身的IP保持通信
    /sbin/route add -host $VIP dev lo:0
    echo "LVS-DR real server starts successfully.\n"
    ;;
stop)
    /sbin/ifconfig lo:0 down
    /sbin/route del $VIP >/dev/null 2>&1
    echo "1" >/proc/sys/net/ipv4/conf/lo/arp_ignore
    echo "2" >/proc/sys/net/ipv4/conf/lo/arp_announce
    echo "1" >/proc/sys/net/ipv4/conf/all/arp_ignore
    echo "2" >/proc/sys/net/ipv4/conf/all/arp_announce
echo "LVS-DR real server stopped.\n"
    ;;
status)
    isLoOn=`/sbin/ifconfig lo:0 | grep "$VIP"`
    isRoOn=`/bin/netstat -rn | grep "$VIP"`
    if [ "$isLoON" == "" -a "$isRoOn" == "" ]; then
        echo "LVS-DR real server has run yet."
    else
        echo "LVS-DR real server is running."
    fi
    exit 3
    ;;
*)
    echo "Usage: $0 {start|stop|status}"
    exit 1
esac
exit 0
[root@mysql-master ~]# chmod 755 realserver
[root@mysql-master ~]# service realserver start
[root@mysql-slave ~]# chmod 755 realserver
[root@mysql-slave ~]# service realserver start


Definido para iniciar na inicialização

echo "/etc/init.d/realserver" >> /etc/rc.d/rc.local

Insira a descrição da imagem aqui
Insira a descrição da imagem aqui

teste

Adicionar um usuário de teste

mysql> grant all on *.* to 'zyy'@'%' identified by 'zyy' ;
Query OK, 0 rows affected, 1 warning (0.00 sec)

1. Verifique a estratégia de encaminhamento de balanceamento de carga LVS

    MySQL客户端使用VIP连接数据库,并查看所连接的数据库服务器ID。可以看到,每次执行依次连接到192.168.30.246和192.168.30.245的MySQL,证明是轮询策略产生的结果。

Insira a descrição da imagem aqui


2. Simule a falha mestre dos lvs

Pare de manter-se vivo no lado mestre

[root@keep-master ~]# systemctl stop keepalived

Você pode ver que o VIP mudou
Insira a descrição da imagem aqui

Insira a descrição da imagem aqui

Conecte-se ao MySQL neste momento e o balanceamento de carga não será afetado.
Insira a descrição da imagem aqui

3. Simule se um dos bancos de dados está inativo

Fechar o banco de dados do escravo

[root@mysql-slave ~]# service mysqld stop 
Shutting down MySQL............ SUCCESS! 


[root@mysql-slave ~]# ss -anlt
State      Recv-Q Send-Q Local Address:Port               Peer Address:Port              
LISTEN     0      128     *:22                  *:*                  
LISTEN     0      128    :::22                 :::*                 

No momento, apenas o banco de dados mysql-master está funcionando, mas pode garantir negócios ininterruptos
Insira a descrição da imagem aqui

Acho que você gosta

Origin blog.csdn.net/zyy130988/article/details/108541939
Recomendado
Clasificación