MySQL双主一从高可用

news2025/7/16 4:36:04

MySQL双主一从高可用

文章目录

  • MySQL双主一从高可用
    • 环境说明
      • 1.配置前的准备工作
      • 2.配置yum源
    • 1.在部署NFS服务
    • 2.安装主数据库的数据库服务,并挂载nfs
    • 3.初始化数据库
    • 4.配置两台master主机数据库
    • 5.配置m1和m2成为主数据库
    • 6.安装、配置keepalived
    • 7.安装部署从数据库
    • 8.测试
        • 1.在高可用集群中,当master1主机为主时,master2主机为备
        • 2.模拟master1主机发生故障,导致服务宕机,master1主机上的keepalived服务则会自动关闭,释放资源,vip则会跳转到master2主机上,从而使得master2主机接替主数据库位置,开启mysql服务

环境说明

nfs服务器用于同步两台主服务器的数据,确保一致。

主机名称IP地址充当角色所需软件操作系统
nfs192.168.195.133NFS服务器nfscentos 8
master1192.168.195.134mysql主服务器(主节点)mysql、keepalivedcentos 8
master2192.168.195.135mysql主服务器(备节点)mysql、keepalivedcentos 8
slave192.168.195.136mysql从服务器mysqlcentos 8

1.配置前的准备工作

永久关闭所有主机的防火墙和selinux

//nfs主机
[root@nfs ~]# systemctl disable --now firewalld.service 
Removed /etc/systemd/system/multi-user.target.wants/firewalld.service.
Removed /etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service.
[root@nfs ~]# sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config 
[root@nfs ~]# reboot

//master1主机
[root@master1 ~]# systemctl disable --now firewalld.service 
Removed /etc/systemd/system/multi-user.target.wants/firewalld.service.
Removed /etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service.
[root@master1 ~]# sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config
[root@master1 ~]# reboot

//master2主机
[root@master2 ~]# systemctl disable --now firewalld.service 
Removed /etc/systemd/system/multi-user.target.wants/firewalld.service.
Removed /etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service.
[root@master2 ~]# sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config
[root@master2 ~]# reboot

//slave主机
[root@slave ~]# systemctl disable --now firewalld.service 
Removed /etc/systemd/system/multi-user.target.wants/firewalld.service.
Removed /etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service.
[root@slave ~]# sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config
[root@slave ~]# reboot

2.配置yum源

master主机加上epel源

推荐使用阿里云源
//nfs主机
[root@nfs ~]# rm -rf /etc/yum.repos.d/*
[root@nfs ~]# curl -o /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-vault-8.5.2111.repo 
[root@nfs ~]# yum clean all
[root@nfs ~]# yum makecache 

//master1主机
[root@master1 ~]# rm -rf /etc/yum.repos.d/*
[root@master1 ~]# curl -o /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-vault-8.5.2111.repo
[root@master1 ~]# yum -y install epel-release wget vim
[root@master1 ~]# yum clean all
[root@master1 ~]# yum makecache

//master2主机
[root@master2 ~]# rm -rf /etc/yum.repos.d/*
[root@master2 ~]# curl -o /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-vault-8.5.2111.repo
[root@master2 ~]# yum -y install epel-release wget vim
[root@master2 ~]# yum clean all
[root@master2 ~]# yum makecache

//slave主机
[root@slave ~]# rm -rf /etc/yum.repos.d/*
[root@slave ~]# curl -o /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-vault-8.5.2111.repo
[root@slave ~]# yum clean all
[root@slave ~]# yum makecache

1.在部署NFS服务

在nfs主机上部署nfs服务

//安装nfs服务
[root@nfs ~]# yum -y install nfs-utils.x86_64

//创建一个共享目录
[root@nfs ~]# mkdir /opt/data
[root@nfs ~]# vim /etc/exports
[root@nfs ~]# cat /etc/exports
/opt/data 192.168.195.133(rw,sync,no_root_squash)
/opt/data 192.168.195.134(rw,sync,no_root_squash)

//启动服务
[root@nfs ~]# systemctl restart rpcbind.service
[root@nfs ~]# systemctl restart nfs-server.service
[root@nfs ~]# systemctl enable --now nfs-server.service
Created symlink /etc/systemd/system/multi-user.target.wants/nfs-server.service → /usr/lib/systemd/system/nfs-server.service.

2.安装主数据库的数据库服务,并挂载nfs

在master1和master2上安装mysql数据库

在master1主机上:
在这里插入图片描述

//创建mysql用户
[root@master1 ~]# groupadd -r -g 306 mysql
[root@master1 ~]# useradd -r -M -s /sbin/nologin -g 306 -u 306 mysql

//解压mysql二进制包
[root@master1 ~]# ls
anaconda-ks.cfg  mysql-5.7.39-linux-glibc2.12-x86_64.tar.gz
[root@master1 ~]# tar xf mysql-5.7.39-linux-glibc2.12-x86_64.tar.gz -C /usr/local/
[root@master1 ~]# ln -sv /usr/local/mysql-5.7.39-linux-glibc2.12-x86_64/ /usr/local/mysql
'/usr/local/mysql' -> '/usr/local/mysql-5.7.39-linux-glibc2.12-x86_64/'

//修改mysql目录属主属组,并添加环境变量
[root@master1 ~]# chown mysql:mysql /usr/local/mysql
[root@master1 ~]# echo 'export PATH=/usr/local/mysql/bin:$PATH' > /etc/profile.d/mysql.sh
[root@master1 ~]# source /etc/profile.d/mysql.sh
[root@master1 ~]# echo $PATH
/usr/local/mysql/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin

//建立数据存放目录
[root@master1 ~]# mkdir /opt/data
[root@master1 ~]# chown -R mysql:mysql /opt/data/

//挂载nfs上的/opt/data目录,以便同步
[root@master1 ~]# yum -y install nfs-utils.x86_64
[root@master1 ~]# systemctl enable --now nfs-server.service 
Created symlink /etc/systemd/system/multi-user.target.wants/nfs-server.service → /usr/lib/systemd/system/nfs-server.service.
[root@master1 ~]# mount -t nfs 192.168.195.133:/opt/data /opt/data

//配置头文件和lib库文件路径
[root@master1 ~]# ln -sv /usr/local/mysql/include/ /usr/local/include/mysql
'/usr/local/include/mysql' -> '/usr/local/mysql/include/'
[root@master1 ~]# echo '/usr/local/mysql/lib' > /etc/ld.so.conf.d/mysql.conf
[root@master1 ~]# ldconfig

//生成mysql配置文件/etc/my.cnf
[root@master1 ~]# vim /etc/my.cnf
[root@master1 ~]# 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
[root@master1 ~]#

//配置服务启动脚本
[root@master1 ~]# cp -a /usr/local/mysql/support-files/mysql.server /etc/init.d/mysqld
[root@master1 ~]# sed -ri 's#^(basedir=).*#\1/usr/local/mysql#g' /etc/init.d/mysqld
[root@master1 ~]# sed -ri 's#^(datadir=).*#\1/opt/data#g' /etc/init.d/mysqld

在master2主机上:

//创建mysql用户
[root@master2 ~]# groupadd -r -g 306 mysql
[root@master2 ~]# useradd -r -M -s /sbin/nologin -g 306 -u 306 mysql

//解压mysql二进制包(将master1主机上的mysql二进制包用scp命令传送过来)
[root@master1 ~]# scp mysql-5.7.39-linux-glibc2.12-x86_64.tar.gz root@192.168.195.135:/root/
The authenticity of host '192.168.195.135 (192.168.195.135)' can't be established.
ECDSA key fingerprint is SHA256:rX8qo9h9J++q89dUg33ZnWDL7KT30i/It603EM37Mic.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '192.168.195.135' (ECDSA) to the list of known hosts.
root@192.168.195.135's password: 
mysql-5.7.39-linux-glibc2.12-x86_64.tar.gz                                   100%  645MB 127.1MB/s   00:05    
[root@master2 ~]# ls
anaconda-ks.cfg  mysql-5.7.39-linux-glibc2.12-x86_64.tar.gz
[root@master2 ~]# tar xf mysql-5.7.39-linux-glibc2.12-x86_64.tar.gz -C /usr/local/
[root@master2 ~]# ln -sv /usr/local/mysql-5.7.39-linux-glibc2.12-x86_64/ /usr/local/mysql
'/usr/local/mysql' -> '/usr/local/mysql-5.7.39-linux-glibc2.12-x86_64/'
[root@master2 ~]# ll /usr/local/
total 0
drwxr-xr-x. 2 root root   6 Aug 12  2018 bin
drwxr-xr-x. 2 root root   6 Aug 12  2018 etc
drwxr-xr-x. 2 root root   6 Aug 12  2018 games
drwxr-xr-x. 2 root root   6 Aug 12  2018 include
drwxr-xr-x. 2 root root   6 Aug 12  2018 lib
drwxr-xr-x. 2 root root   6 Aug 12  2018 lib64
drwxr-xr-x. 2 root root   6 Aug 12  2018 libexec
lrwxrwxrwx  1 root root  47 Oct 15 18:50 mysql -> /usr/local/mysql-5.7.39-linux-glibc2.12-x86_64/
drwxr-xr-x  9 root root 129 Oct 15 18:50 mysql-5.7.39-linux-glibc2.12-x86_64
drwxr-xr-x. 2 root root   6 Aug 12  2018 sbin
drwxr-xr-x. 5 root root  49 Jul 20 11:33 share
drwxr-xr-x. 2 root root   6 Aug 12  2018 src

//修改mysql目录的属主属组,并添加环境变量
[root@master2 ~]# chown -R mysql:mysql /usr/local/mysql
[root@master2 ~]# echo 'export PATH=/usr/local/mysql/bin:$PATH' > /etc/profile.d/mysql.sh 
[root@master2 ~]# source /etc/profile.d/mysql.sh
[root@master2 ~]# echo $PATH
/usr/local/mysql/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin

//建立数据存放目录
[root@master2 ~]# mkdir /opt/data
[root@master2 ~]# chown -R mysql:mysql /opt/data/

//挂载nfs上的/opt/data目录,以便同步
[root@master2 ~]# yum -y install nfs-utils.x86_64
[root@master2 ~]# systemctl enable --now nfs-server.service
Created symlink /etc/systemd/system/multi-user.target.wants/nfs-server.service → /usr/lib/systemd/system/nfs-server.service.
[root@master2 ~]# mount -t nfs 192.168.195.133:/opt/data /opt/data

//配置头文件和lib库文件路径
[root@master2 ~]# ln -sv /usr/local/mysql/include/ /usr/local/include/mysql
'/usr/local/include/mysql' -> '/usr/local/mysql/include/'
[root@master2 ~]# echo '/usr/local/mysql/lib' > /etc/ld.so.conf.d/mysql.conf
[root@master2 ~]# ldconfig

//生成配置文件
[root@master2 ~]# vim /etc/my.cnf
[root@master2 ~]# 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

//配置脚本启动服务
[root@master2 ~]# cp -a /usr/local/mysql/support-files/mysql.server /etc/init.d/mysqld 
[root@master2 ~]# sed -ri 's#^(basedir=).*#\1/usr/local/mysql#g' /etc/init.d/mysqld
[root@master2 ~]# sed -ri 's#^(datadir=).*#\1/opt/data#g' /etc/init.d/mysqld

3.初始化数据库

由于我们配置了nfs同步两台主机的/opt/data目录,所以只需在其中一台上初始化数据库即可,另一台会
自动同步/opt/data目录下的文件

在master1主机上初始化数据库

[root@master1 ~]# /usr/local/mysql/bin/mysqld --initialize --user=mysql --datadir=/opt/data/
2023-10-15T13:09:26.800119Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
2023-10-15T13:09:27.203177Z 0 [Warning] InnoDB: New log files created, LSN=45790
2023-10-15T13:09:27.264266Z 0 [Warning] InnoDB: Creating foreign key constraint system tables.
2023-10-15T13:09:27.322831Z 0 [Warning] No existing UUID has been found, so we assume that this is the first time that this server has been started. Generating a new UUID: 11b3dfb4-6b5c-11ee-9bf0-000c298b9baf.
2023-10-15T13:09:27.325547Z 0 [Warning] Gtid table is not ready to be used. Table 'mysql.gtid_executed' cannot be opened.
2023-10-15T13:09:27.589254Z 0 [Warning] A deprecated TLS version TLSv1 is enabled. Please use TLSv1.2 or higher.
2023-10-15T13:09:27.589289Z 0 [Warning] A deprecated TLS version TLSv1.1 is enabled. Please use TLSv1.2 or higher.
2023-10-15T13:09:27.593109Z 0 [Warning] CA certificate ca.pem is self signed.
2023-10-15T13:09:27.644471Z 1 [Note] A temporary password is generated for root@localhost: gyOij-dGi0K#   //最后一行随机生成一个密码(“gyOij-dGi0K#”)

//查看nfs主机和两台master主机的/opt/data目录的内容
nfs主机
[root@nfs ~]# ls /opt/data/
auto.cnf    client-cert.pem  ibdata1      mysql               public_key.pem   sys
ca-key.pem  client-key.pem   ib_logfile0  performance_schema  server-cert.pem
ca.pem      ib_buffer_pool   ib_logfile1  private_key.pem     server-key.pem

master1主机
[root@master1 ~]# ls /opt/data/
auto.cnf    client-cert.pem  ibdata1      mysql               public_key.pem   sys
ca-key.pem  client-key.pem   ib_logfile0  performance_schema  server-cert.pem
ca.pem      ib_buffer_pool   ib_logfile1  private_key.pem     server-key.pem

master2主机
[root@master2 ~]# ls /opt/data/
auto.cnf    client-cert.pem  ibdata1      mysql               public_key.pem   sys
ca-key.pem  client-key.pem   ib_logfile0  performance_schema  server-cert.pem
ca.pem      ib_buffer_pool   ib_logfile1  private_key.pem     server-key.pem

4.配置两台master主机数据库

//先在两台主机上安装一个库文件包
[root@master1 ~]# yum -y install ncurses-compat-libs

[root@master2 ~]# yum -y install ncurses-compat-libs

//首先启动master1主机的数据库服务,由于两个数据库完全一模一样,所以只可以启动一台,不可以同时启动
[root@master1 ~]# service mysqld start
Starting MySQL.Logging to '/opt/data/master1.err'.
SUCCESS!
[root@master1 ~]#
 
//使用初始密码登录,设置密码
[root@master1 ~]# mysql -uroot -p"gyOij-dGi0K#"
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.7.39

Copyright (c) 2000, 2022, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> set password = password('12345678');
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> quit
Bye
[root@master1 ~]# 

在master2主机上通过在master1给mysql设置的密码登录数据库

//首先需要关闭master1主机上的mysql服务
[root@master1 ~]# service mysqld stop
Shutting down MySQL.. SUCCESS! 
[root@master1 ~]#

//启动m2的数据库服务
[root@master2 ~]# service mysqld start 
Starting MySQL.Logging to '/opt/data/master2.err'.
 SUCCESS! 
[root@master2 ~]#

//尝试使用修改过后的密码登录m2的数据库
[root@master2 ~]# mysql -uroot -p12345678
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.7.39 MySQL Community Server (GPL)

Copyright (c) 2000, 2022, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> quit
Bye                   //可以登录
[root@master2 ~]#

//测试完后,关闭m2的数据库服务
[root@master2 ~]# service mysqld stop
Shutting down MySQL.. SUCCESS! 
[root@master2 ~]#

5.配置m1和m2成为主数据库

master1主机
[root@master1 ~]# mysql -uroot -p12345678
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.7.39 MySQL Community Server (GPL)

Copyright (c) 2000, 2022, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> grant replication slave on *.* to 'ftx'@'192.168.195.136' identified by '12345678';                    //创建一个同步账号授权给从数据库使用
Query OK, 0 rows affected, 1 warning (0.01 sec)

mysql> flush privileges;   //重读授权表
Query OK, 0 rows affected (0.00 sec)

mysql> quit
Bye
[root@master1 ~]#

//修改配置文件
[root@master1 ~]# vim /etc/my.cnf
[root@master1 ~]# 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-bin=mysql_bin   //添加此行
server-id=10        //添加此行,id全局唯一,不可重复

//重启服务
[root@master1 ~]# service mysqld stop 
Shutting down MySQL.. SUCCESS! 
[root@master1 ~]# service mysqld start 
Starting MySQL. SUCCESS! 
[root@master1 ~]#

//然后关闭服务,确保两台master主机只启动一台
[root@master1 ~]# service mysqld stop 
Shutting down MySQL.. SUCCESS! 
[root@master1 ~]#

//配置master2主机,由于/opt/data的是同步的,所以不需要再创建用户授权,只用改配置文件
[root@master2 ~]# vim /etc/my.cnf
[root@master2 ~]# 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-bin=mysql_bin      //添加此行
server-id=11           //添加此行,id全局唯一,不可重复

//重启服务,然后关闭服务
[root@master2 ~]# service mysqld start 
Starting MySQL. SUCCESS! 
[root@master2 ~]# service mysqld stop
Shutting down MySQL.. SUCCESS! 
[root@master2 ~]#

6.安装、配置keepalived

master1主机

//在master1主机上安装keepalived服务
[root@master1 ~]# yum -y install keepalived.x86_64

//在master1主机上配置keepalived所需脚本
[root@master1 ~]# mkdir /scripts && cd /scripts
[root@master1 scripts]# vim check_mysql.sh
[root@master1 scripts]# chmod +x check_mysql.sh
[root@master1 scripts]# cat check_mysql.sh  //该脚本得出是否存在mysql服务进程,若没有,则进入判断,执行关闭keepalived服务的命令
#!/bin/bash

mysql_status=$(ps -ef | grep -Ev "grep|$0" | grep '\bmysql\b'|wc -l)

if [ $mysql_status -lt 1 ];then
systemctl stop keepalived
fi

[root@master1 scripts]# ll
total 4
-rwxr-xr-x 1 root root 145 Oct 15 22:25 check_mysql.sh

//先将原配置文件备份一下,然后修改,生成一个新的配置文件
[root@master1 ~]# cp /etc/keepalived/keepalived.conf /opt/
[root@master1 ~]# vim /etc/keepalived/keepalived.conf 
[root@master1 ~]# cat /etc/keepalived/keepalived.conf 
! Configuration File for keepalived

global_defs {
     router_id mysql1                   //路由器id,两台主机要不一样
}

vrrp_script check_mysql {
    script "/scripts/check_mysql.sh"    //脚本的路径
    interval 1
    fall 3
    weight -40
}

vrrp_instance VI_1 {
    state MASTER                      //初始状态MASTER或BACKUP
    interface ens160                  //vrrp示例绑定的网卡接口,和真实网卡一致
    virtual_router_id 80              //虚拟路由器id,两台主机要一样
    priority 100                      //优先级,优先级越大就是主服务器
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 12345678           //密码,可以自定义
    }
    virtual_ipaddress {
        192.168.195.100              //vip
    }
    track_script {
        check_mysql                 //追踪的脚本
    }
}

virtual_server 192.168.195.100 80 {             //配置虚拟服务器
    delay_loop 6                                //健康检查时间间隔
    lb_algo rr                                  //lvs调度算法
    lb_kind NAT                                 //lvs模式
    persistence_timeout 50                      //持久化超时时间,单位为秒
    protocol TCP

    real_server 192.168.195.134 80 {            //指向第1台主数据库的ip(master1主机)
        weight 1
        TCP_CHECK {
            connect_port 3306
            connect_timeout 3
            nb_get_retry 3
            delay_before_retry 3
        }
    }
    real_server 192.168.195.135 80 {           //指向第2台主数据库的ip(master2主机)
        weight 1
        TCP_CHECK {
            connect_port 3306
            connect_timeout 3
            nb_get_retry 3
            delay_before_retry 3
        }
    }
}
[root@master1 ~]#

//重启keepalived服务,以重读keepalived配置文件
[root@master1 ~]# systemctl restart keepalived.service

master2主机

//在master2主机上安装keepalived服务
[root@master2 ~]# yum -y install keepalived.x86_64

//在master2主机上配置keepalived所需脚本
[root@master2 ~]# mkdir /scripts && cd /scripts
[root@master2 scripts]# vim notify.sh
[root@master2 scripts]# chmod +x notify.sh
[root@master2 scripts]# cat notify.sh 
#!/bin/bash

case "$1" in
  master)
        mysql_status=$(ps -ef|grep -Ev "grep|$0"|grep '\bmysql\b'|wc -l)
        if [ $mysql_status -lt 1 ];then
            service mysqld start
        fi
  ;;
  backup)
        mysql_status=$(ps -ef|grep -Ev "grep|$0"|grep '\bmysql\b'|wc -l)
        if [ $mysql_status -gt 0 ];then
        service mysqld stop
        fi
  ;;
  *)
        echo "Usage:$0 master|backup"
  ;;
esac

[root@master2 scripts]# ll
total 4
-rwxr-xr-x 1 root root 419 Oct 15 22:48 notify.sh

//先将原配置文件备份一下,然后修改,生成一个新的配置文件
[root@master2 ~]# cp /etc/keepalived/keepalived.conf /opt/
[root@master2 ~]# vim /etc/keepalived/keepalived.conf
[root@master2 ~]# cat /etc/keepalived/keepalived.conf
! Configuration File for keepalived

global_defs {
   router_id mysql2
}

vrrp_instance VI_1 {
    state BACKUP
    interface ens160
    virtual_router_id 80
    priority 80
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 12345678
    }
    virtual_ipaddress {
        192.168.195.100
    }
    notify_master "/scripts/notify.sh master"
    notify_backup "/scripts/notify.sh backup"
}

virtual_server 192.168.195.100 80 {
    delay_loop 6
    lb_algo rr
    lb_kind NAT
    persistence_timeout 50
    protocol TCP

    real_server 192.168.195.134 80 {
        weight 1
        TCP_CHECK {
            connect_port 80
            connect_timeout 3
            nb_get_retry 3
            delay_before_retry 3
          }
        }
    real_server 192.168.195.135 80 {
        weight 1
        TCP_CHECK {
            connect_port 80 
            connect_timeout 3
            nb_get_retry 3
            delay_before_retry 3
          }
        }
}
[root@master2 ~]#

//重启服务,以重读配置文件
[root@master2 ~]# systemctl restart keepalived.service

查看vip

我们先手动开启master1主机的mysql服务和keepalived服务,开启master1主机上的mysql服务之前需关闭master2主机上的mysql服务

//当前在我们的mysql服务和keepalived服务都开启的状态下,存在vip
[root@master1 ~]# systemctl is-active keepalived.service 
active
[root@master1 ~]# ss -antl | grep 3306
LISTEN    0         80                       *:3306                   *:*
[root@master1 ~]# ip a show ens160 | grep 192.168.195.100
    inet 192.168.195.100/32 scope global ens160
[root@master1 ~]# ip a show ens160 | grep 192.168.195.100 | wc -l
1

//查看master2主机上的服务状态,应该是keepalived启动,mysql未启动,没有vip
[root@master2 ~]# systemctl is-active keepalived.service 
active
[root@master2 ~]# ss -antl | grep 3306
[root@master2 ~]# ss -antl | grep 3306 | wc -l
0
[root@master2 ~]# ip a show ens160 | grep 192.168.195.100
[root@master2 ~]# ip a show ens160 | grep 192.168.195.100 | wc -l
0

7.安装部署从数据库

在slave主机上

//安装一个库文件包
[root@slave ~]# yum -y install ncurses-compat-libs

//创建mysql用户和组
[root@slave ~]# groupadd -r -g 306 mysql
[root@slave ~]#  useradd -r -M -s /sbin/nologin -g 306 -u 306 mysql

//解压二进制包到/usr/local/
[root@master1 ~]# scp mysql-5.7.39-linux-glibc2.12-x86_64.tar.gz  root@192.168.195.136:/root/
root@192.168.195.136's password: 
mysql-5.7.39-linux-glibc2.12-x86_64.tar.gz                                   100%  645MB 122.6MB/s   00:05
[root@slave ~]# ls
anaconda-ks.cfg  mysql-5.7.39-linux-glibc2.12-x86_64.tar.gz
[root@slave ~]# tar xf mysql-5.7.39-linux-glibc2.12-x86_64.tar.gz -C /usr/local/

//创建目录链接,并修改目录/usr/local/mysql的属主属组
[root@slave ~]# ln -sv /usr/local/mysql-5.7.39-linux-glibc2.12-x86_64/ /usr/local/mysql 
'/usr/local/mysql' -> '/usr/local/mysql-5.7.39-linux-glibc2.12-x86_64/'
[root@slave ~]# chown -R mysql:mysql /usr/local/mysql
[root@slave ~]# ll -d /usr/local/mysql
lrwxrwxrwx 1 mysql mysql 47 Oct 15 23:16 /usr/local/mysql -> /usr/local/mysql-5.7.39-linux-glibc2.12-x86_64/

//添加环境变量
[root@slave ~]# echo 'export PATH=/usr/local/mysql/bin:$PATH' > /etc/profile.d/mysql.sh
[root@slave ~]# source /etc/profile.d/mysql.sh
[root@slave ~]# echo $PATH
/usr/local/mysql/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin

//建立数据存放目录
[root@slave ~]# mkdir /opt/data
[root@slave ~]# chown -R mysql:mysql /opt/data/

//初始化数据库
[root@slave ~]# /usr/local/mysql/bin/mysqld --initialize --user=mysql --datadir=/opt/data/ 
2023-10-15T15:19:37.491589Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
2023-10-15T15:19:37.612968Z 0 [Warning] InnoDB: New log files created, LSN=45790
2023-10-15T15:19:37.634355Z 0 [Warning] InnoDB: Creating foreign key constraint system tables.
2023-10-15T15:19:37.688134Z 0 [Warning] No existing UUID has been found, so we assume that this is the first time that this server has been started. Generating a new UUID: 410b0a73-6b6e-11ee-8f2f-000c29d9f7e8.
2023-10-15T15:19:37.688743Z 0 [Warning] Gtid table is not ready to be used. Table 'mysql.gtid_executed' cannot be opened.
2023-10-15T15:19:38.020453Z 0 [Warning] A deprecated TLS version TLSv1 is enabled. Please use TLSv1.2 or higher.
2023-10-15T15:19:38.020499Z 0 [Warning] A deprecated TLS version TLSv1.1 is enabled. Please use TLSv1.2 or higher.
2023-10-15T15:19:38.020906Z 0 [Warning] CA certificate ca.pem is self signed.
2023-10-15T15:19:38.127308Z 1 [Note] A temporary password is generated for root@localhost: ZKyqhRghv0/Y   //最后一行随机生成一个登录mysql数据库密码:(“ZKyqhRghv0/Y”)

//配置头文件和lib库文件路径
[root@slave ~]# ln -sv /usr/local/mysql/include/ /usr/local/include/mysql
'/usr/local/include/mysql' -> '/usr/local/mysql/include/'
[root@slave ~]# echo '/usr/local/mysql/lib' > /etc/ld.so.conf.d/mysql.conf
[root@slave ~]# ldconfig

//生成mysql配置文件
[root@slave ~]# vim /etc/my.cnf
[root@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
server-id=20
relay-log=mysql_relay_bin 
[root@slave ~]#

//配置服务启动脚本
[root@slave ~]# cp -a /usr/local/mysql/support-files/mysql.server /etc/init.d/mysqld
[root@slave ~]# sed -ri 's#^(basedir=).*#\1/usr/local/mysql#g' /etc/init.d/mysqld
[root@slave ~]# sed -ri 's#^(datadir=).*#\1/opt/data#g' /etc/init.d/mysqld

//重新设置mysql数据库密码
[root@slave ~]# mysql -uroot -p"ZKyqhRghv0/Y"
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.7.39

Copyright (c) 2000, 2022, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> set password = password('12345678');
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> quit
Bye
[root@slave ~]#

配置从库slave模式

查看master1主机上的master状态
在这里插入图片描述

//认vip为主(192.168.195.100)
[root@slave ~]# mysql -uroot -p12345678
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 3
Server version: 5.7.39 MySQL Community Server (GPL)

Copyright (c) 2000, 2022, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> change master to master_host='192.168.195.100',
    -> master_user='ftx',
    -> master_password='12345678',
    -> master_log_file='mysql_bin.000004',
    -> master_log_pos=154;
Query OK, 0 rows affected, 2 warnings (0.01 sec)

mysql> start slave;          //启动主从复制
Query OK, 0 rows affected (0.00 sec)

//查看从数据库的状态
mysql> show slave status\G   
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 192.168.195.100
                  Master_User: ftx
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql_bin.000004
          Read_Master_Log_Pos: 154
               Relay_Log_File: mysql_relay_bin.000002
                Relay_Log_Pos: 320
        Relay_Master_Log_File: mysql_bin.000004
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
              Replicate_Do_DB: 
          Replicate_Ignore_DB: 
           Replicate_Do_Table: 
       Replicate_Ignore_Table: 
      Replicate_Wild_Do_Table: 
  Replicate_Wild_Ignore_Table: 
                   Last_Errno: 0
                   Last_Error: 
                 Skip_Counter: 0
          Exec_Master_Log_Pos: 154
              Relay_Log_Space: 527
              Until_Condition: None
               Until_Log_File: 
                Until_Log_Pos: 0
           Master_SSL_Allowed: No
           Master_SSL_CA_File: 
           Master_SSL_CA_Path: 
              Master_SSL_Cert: 
            Master_SSL_Cipher: 
               Master_SSL_Key: 
        Seconds_Behind_Master: 0
Master_SSL_Verify_Server_Cert: No
                Last_IO_Errno: 0
                Last_IO_Error: 
               Last_SQL_Errno: 0
               Last_SQL_Error: 
  Replicate_Ignore_Server_Ids: 
             Master_Server_Id: 10
                  Master_UUID: 11b3dfb4-6b5c-11ee-9bf0-000c298b9baf
             Master_Info_File: /opt/data/master.info
                    SQL_Delay: 0
          SQL_Remaining_Delay: NULL
      Slave_SQL_Running_State: Slave has read all relay log; waiting for more updates
           Master_Retry_Count: 86400
                  Master_Bind: 
      Last_IO_Error_Timestamp: 
     Last_SQL_Error_Timestamp: 
               Master_SSL_Crl: 
           Master_SSL_Crlpath: 
           Retrieved_Gtid_Set: 
            Executed_Gtid_Set: 
                Auto_Position: 0
         Replicate_Rewrite_DB: 
                 Channel_Name: 
           Master_TLS_Version: 
1 row in set (0.00 sec)

mysql>

8.测试

1.在高可用集群中,当master1主机为主时,master2主机为备
//master1主机上的keepalived服务和mysql是启动的,有vip
[root@master1 ~]# systemctl is-active keepalived.service
active
[root@master1 ~]# ss -antl | grep 3306
LISTEN    0         80                       *:3306                   *:*       
[root@master1 ~]# ip a show ens160 | grep 192.168.195.100
    inet 192.168.195.100/32 scope global ens160
[root@master1 ~]# ip a show ens160 | grep 192.168.195.100 | wc -l
1

//而此时master2主机上的则是keepalived服务开启,mysql服务关闭,没有vip
[root@master2 ~]# systemctl is-active keepalived.service 
active
[root@master2 ~]# ss -antl | grep 3306
[root@master2 ~]# ss -antl | grep 3306 | wc -l
0
[root@master2 ~]# ip a show ens160 | grep 192.168.195.100
[root@master2 ~]# ip a show ens160 | grep 192.168.195.100 | wc -l
0

//在master1主机上的mysql数据库中,创建一个数据库,然后查看从服务器是否同步
[root@master1 ~]# mysql -uroot -p12345678 -e "create database ftx;"
mysql: [Warning] Using a password on the command line interface can be insecure.
[root@master1 ~]# mysql -uroot -p12345678 -e "show databases;"
mysql: [Warning] Using a password on the command line interface can be insecure.
+--------------------+
| Database           |
+--------------------+
| information_schema |
| ftx                |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
上述告警是告诉我们在命令行界面输入密码不安全,此此实验我们不用考虑这个问题

//前往slave主机上查看
[root@slave ~]# mysql -uroot -p12345678 -e "show databases;"
mysql: [Warning] Using a password on the command line interface can be insecure.
+--------------------+
| Database           |
+--------------------+
| information_schema |
| ftx                |    //成功创建
| mysql              |
| performance_schema |
| sys                |
+--------------------+
2.模拟master1主机发生故障,导致服务宕机,master1主机上的keepalived服务则会自动关闭,释放资源,vip则会跳转到master2主机上,从而使得master2主机接替主数据库位置,开启mysql服务
//手动关闭master1主机上的mysql服务,从而使得keepalived服务自动关闭释放资源
[root@master1 ~]# service mysqld stop 
Shutting down MySQL............ SUCCESS! 
[root@master1 ~]# systemctl is-active keepalived.service 
inactive
[root@master1 ~]# ss -antl | grep 3306
[root@master1 ~]# ss -antl | grep 3306 | wc -l
0
[root@master1 ~]# ip a show ens160 | grep 192.168.195.100
[root@master1 ~]# ip a show ens160 | grep 192.168.195.100 | wc -l
0

//再次查看master2主机上mysql和keepalived服务状态,以及vip位置
[root@master2 ~]# systemctl is-active keepalived.service 
active
[root@master2 ~]# ss -antl | grep 3306
LISTEN    0         80                       *:3306                   *:*       
[root@master2 ~]# ss -antl | grep 3306 | wc -l
1
[root@master2 ~]# ip a show ens160 | grep 192.168.195.100
    inet 192.168.195.100/32 scope global ens160
[root@master2 ~]# ip a show ens160 | grep 192.168.195.100 | wc -l
1

//在master2主机上登录mysql数据库,创建一个数据库,查看从服务器是否同步
[root@master2 ~]# mysql -uroot -p12345678 -e "create database yyr;"
mysql: [Warning] Using a password on the command line interface can be insecure.
[root@master2 ~]# mysql -uroot -p12345678 -e "show databases;"
mysql: [Warning] Using a password on the command line interface can be insecure.
+--------------------+
| Database           |
+--------------------+
| information_schema |
| ftx                |
| mysql              |
| performance_schema |
| sys                |
| yyr                |
+--------------------+

//前往slave主机上查看
[root@slave ~]# mysql -uroot -p12345678 -e "show databases;"
mysql: [Warning] Using a password on the command line interface can be insecure.
+--------------------+
| Database           |
+--------------------+
| information_schema |
| ftx                |
| mysql              |
| performance_schema |
| sys                |
| yyr                |       //成功创建
+--------------------+

部署完成

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1102855.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

leetcode-200. 岛屿数量

1. 题目 leetcode题目链接 2. 解答 思路: 需要循环遍历每个节点;找到陆地,基于陆地开始遍历陆地的上下左右;数组dirm dirn就可以表示某个区域的上下左右;标记遍历过的节点;设计循环的退出条件&#xf…

Kotlin中的比较运算符

在Kotlin中,我们可以使用比较运算符进行值的比较和判断。下面对Kotlin中的等于、不等于、小于、大于、小于等于和大于等于进行详细介绍,并提供示例代码。 等于运算符(): 等于运算符用于判断两个值是否相等。如果两个值…

XMLHttpRequest的readyState状态值

readyState状态值 功能:在Ajax请求与服务器响应中,是通过XMLHttpRequest对象完成。而readyState状态值则是记录XMLHttpRequest对象在这个过程进行变化的状态。 readyState状态值readyState分别有5个状态值 0:请求未初始化:在未点击…

微信小程序--数字化会议OA系统之首页搭建

一、Flex弹性布局 布局的传统解决方案,基于盒状模型,依赖 display属性 position属性 float属性。它对于那些特殊布局非常不方便,比如,垂直居中就不容易实现。 2009年,W3C提出了一种新的方案—-Flex布局,可…

python 运算符的优先级:先算乘除,后算加减,有括号的先算括号里面的。

运算符的优先级 什么是运算符的优先级?其实我们小学就已经接触过了,就是在一个表达式中,我们先算谁的问题。 先算乘除,后算加减,有括号的先算括号里面的。 个人建议: ① 不要把一个表达式****写得过于复杂…

【Java基础面试十五】、 说一说你对多态的理解

文章底部有个人公众号:热爱技术的小郑。主要分享开发知识、学习资料、毕业设计指导等。有兴趣的可以关注一下。为何分享? 踩过的坑没必要让别人在再踩,自己复盘也能加深记忆。利己利人、所谓双赢。 面试官:说一说你对多态的理解 …

【Java基础面试十四】、 封装的目的是什么,为什么要有封装?

文章底部有个人公众号:热爱技术的小郑。主要分享开发知识、学习资料、毕业设计指导等。有兴趣的可以关注一下。为何分享? 踩过的坑没必要让别人在再踩,自己复盘也能加深记忆。利己利人、所谓双赢。 面试官: 封装的目的是什么&…

MySQL事务MVCC详解

一、概述 MVCC (MultiVersion Concurrency Control) 叫做多版本并发控制机制。主要是通过数据多版本来实现读-写分离,做到即使有读写冲突时,也能做到不加锁,非阻塞并发读,从而提高数据库并发性能。 MVCC只在已提交读&#xff08…

CCF CSP认证 历年题目自练Day34

题目一 试题编号: 202303-1 试题名称: 田地丈量 时间限制: 1.0s 内存限制: 512.0MB 问题描述: 问题描述 西西艾弗岛上散落着 n 块田地。每块田地可视为平面直角坐标系下的一块矩形区域,由左下角坐标 (x1,…

KNN-近邻算法 及 模型的选择与调优(facebook签到地点预测)

什么是K-近邻算法(K Nearest Neighbors) 1、K-近邻算法(KNN) 1.1 定义 如果一个样本在特征空间中的k个最相似(即特征空间中最邻近)的样本中的大多数属于某一个类别,则该样本也属于这个类别。 来源:KNN算法最早是由Cover和Hart提…

【网络协议】聊聊从物理层到MAC层 ARP 交换机

物理层 物理层其实就是电脑、交换器、路由器、光纤等。组成一个局域网的方式可以使用集线器。可以将多台电脑连接起来,然后进行将数据转发给别的端口。 数据链路层 Hub其实就是广播模式,如果A电脑发出一个包,B、C电脑也可以收到。那么数据…

zk的二阶段提交图解

第一阶段:每次的数据写入事件作为提案广播给所有Follower结点;可以写入的结点返回确认信息ACK;第二阶段:Leader收到一半以上的ACK信息后确认写入可以生效,向所有结点广播COMMIT将提案生效。

Unity 实现一个FPS游戏的全过程

Unity是一款功能强大的游戏引擎,它提供了各种各样的工具和功能,以帮助开发者轻松地创建精美的3D游戏和应用程序。在本文中,我们将使用Unity实现一个FPS游戏的全过程,从场景设计、角色控制、敌人AI到最终的打包发布。 对啦&#x…

开源项目汇总

element-plus 人人开源 人人开源 多租户 若依 jeecg https://gitee.com/jeecg/jeecg?_fromgitee_search#https://gitee.com/link?targethttp%3A%2F%2Fidoc.jeecg.com jeeplus JeePlus快速开发平台 j2eefast Sa-Plus

地震勘探原理部分问题解答

1、二维/三维(陆地/海洋)地震勘探,炮点(激发点)和检波点(接收点)的排布位置如何?画图作答? (1)陆地地震勘探 二维陆地地震野外采集:震…

过滤器(Filter)和拦截器(Interceptor)有什么不同?

过滤器(Filter)和拦截器(Interceptor)是用于处理请求和响应的中间件组件,但它们在实现方式和应用场景上有一些不同。 实现方式: 过滤器是Servlet规范中定义的一种组件,通常以Java类的形式实现。过滤器通过在…

Python文件共享+cpolar内网穿透:轻松实现公网访问

文章目录 1.前言2.本地文件服务器搭建2.1.Python的安装和设置2.2.cpolar的安装和注册 3.本地文件服务器的发布3.1.Cpolar云端设置3.2.Cpolar本地设置 4.公网访问测试5.结语 1.前言 数据共享作为和连接作为互联网的基础应用,不仅在商业和办公场景有广泛的应用&#…

yolov7改进优化之蒸馏(一)

最近比较忙,有一段时间没更新了,最近yolov7用的比较多,总结一下。上一篇yolov5及yolov7实战之剪枝_CodingInCV的博客-CSDN博客 我们讲了通过剪枝来裁剪我们的模型,达到在精度损失不大的情况下,提高模型速度的目的。上一…

6.6 图的应用

思维导图: 6.6.1 最小生成树 ### 6.6 图的应用 #### 主旨:图的概念可应用于现实生活中的许多问题,如网络构建、路径查询、任务排序等。 --- #### 6.6.1 最小生成树 **概念**:要在n个城市中建立通信联络网,则最少需…

【Mysql】Innodb数据结构(四)

概述 MySQL 服务器上负责对表中数据的读取和写入工作的部分是存储引擎 ,而服务器又支持不同类型的存储引擎,比如 InnoDB 、MyISAM 、Memory 等,不同的存储引擎一般是由不同的人为实现不同的特性而开发的,真实数据在不同存储引擎中…