2020-10-18MySQL、Ansible作业(五)

1、如果主节点已经运行了一段时间,且有大量数据时,如何配置并启动slave节点(写出操作步骤)

[16:56:44 root@master ~]#mysqldump -A -F --single-transaction --master-data=1 > /data/full_`date +%F-%T`.sql[16:56:49 root@master ~]#ll /data/  #在主节点备份文件,同时刷新一下二进制日志
total 488
-rw-r--r--  1 root root 487707 Oct 17 16:56 full_2020-10-17-16:56:49.sql
-rw-r--r--. 1 root root   5706 Jun 16 19:42 reset_pro.sh
[16:56:54 root@master ~]#scp /data/full_2020-10-17-16\:56\:49.sql 10.0.0.38:/root/ #将备份拷贝至目标服务器
The authenticity of host '10.0.0.38 (10.0.0.38)' can't be established.
ECDSA key fingerprint is SHA256:B4GojTG9L1h2MUkoY950+2OuTNePsXfMQMtcFn6Z3YE.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '10.0.0.38' (ECDSA) to the list of known hosts.
[email protected]'s password: 
full_2020-10-17-16:56:49.sql                                              100%  476KB  35.3MB/s   00:00 
Welcome to the MariaDB monitor.  Commands end with ; or \g. 
Your MariaDB connection id is 12
Server version: 10.3.17-MariaDB-log MariaDB Server

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

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

MariaDB [(none)]> show master logs; --记录主节点二进制日志位置
+--------------------+-----------+
| Log_name           | File_size |
+--------------------+-----------+
| mariadb-bin.000001 |       379 |
| mariadb-bin.000002 |       424 |
| mariadb-bin.000003 |       375 |
+--------------------+-----------+

MariaDB [(none)]> set global innodb_flush_log_at_trx_commit=2; --优化主节点和从节点的性能
Query OK, 0 rows affected (0.000 sec)

MariaDB [(none)]> set global sync_binlog=0
    -> ;
Query OK, 0 rows affected (0.000 sec)

MariaDB [(none)]> grant replication slave on *.* to repluser@'10.0.0.%' identified by '123456'; --创制只具备复制权限的账号
Query OK, 0 rows affected (0.001 sec)
[16:58:03 root@slave ~]#vi /etc/my.cnf.d/mariadb-server.cnf  #修改从节点数据库配置文件

#
# These groups are read by MariaDB server.
# Use it for options that only the server (but not clients) should see
#
# See the examples of server my.cnf files in /usr/share/mysql/
#

# this is read by the standalone daemon and embedded servers
[server]

# this is only for the mysqld standalone daemon
# Settings user and group are ignored when systemd is used.
# If you need to run mysqld under a different user or group,
# customize your systemd unit file for mysqld/mariadb according to the
# instructions in http://fedoraproject.org/wiki/Systemd
[mysqld]
server-id=2
read-only                                                                                                   
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
log-error=/var/log/mariadb/mariadb.log
pid-file=/run/mariadb/mariadb.pid

[17:05:58 root@slave ~]#systemctl enable --now mariadb #启动从节点数据库
-- MySQL dump 10.17  Distrib 10.3.17-MariaDB, for Linux (x86_64)
--
-- Host: localhost    Database: 
-- ------------------------------------------------------
-- Server version   10.3.17-MariaDB-log

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

--
-- Position to start replication or point-in-time recovery from
--

CHANGE MASTER TO MASTER_HOST='10.0.0.28',
MASTER_USER='repluser',
MASTER_PASSWORD='123456',
MASTER_LOG_FILE='mariadb-bin.000003', MASTER_LOG_POS=375;

...
[17:17:11 root@slave ~]#mysql < full_2020-10-17-16\:56\:49.sql  #恢复数据库
[17:17:23 root@slave ~]#mysql
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 16
Server version: 10.3.17-MariaDB MariaDB Server

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

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

MariaDB [(none)]> start slave; --启动从节点复制线程
Query OK, 0 rows affected (0.002 sec)

MariaDB [(none)]> show slave status\G
*************************** 1. row ***************************
                Slave_IO_State: Waiting for master to send event
                   Master_Host: 10.0.0.28
                   Master_User: repluser
                   Master_Port: 3306
                 Connect_Retry: 60
               Master_Log_File: mariadb-bin.000003
           Read_Master_Log_Pos: 572
                Relay_Log_File: mariadb-relay-bin.000002
                 Relay_Log_Pos: 754
         Relay_Master_Log_File: mariadb-bin.000003
              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: 572
               Relay_Log_Space: 1065
               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: 1
                Master_SSL_Crl: 
            Master_SSL_Crlpath: 
                    Using_Gtid: No
                   Gtid_IO_Pos: 
       Replicate_Do_Domain_Ids: 
   Replicate_Ignore_Domain_Ids: 
                 Parallel_Mode: conservative
                     SQL_Delay: 0
           SQL_Remaining_Delay: NULL
       Slave_SQL_Running_State: Slave has read all relay log; waiting for the slave I/O thread to update it
              Slave_DDL_Groups: 1
Slave_Non_Transactional_Groups: 0
    Slave_Transactional_Groups: 0
1 row in set (0.000 sec)

2、当master服务器宕机,提升一个slave成为新的master(写出操作步骤)

#查看从节点同步记录,找到数据库最新的从节点当新主节点
[19:04:38 root@slave1 ~]#cat /var/lib/mysql/relay-log.info 
5
./mariadb-relay-bin.000002
754
mariadb-bin.000003
572
0

[19:07:55 root@slave1 ~]#vi /etc/my.cnf.d/mariadb-server.cnf  #修改从节点配置文件

#
# These groups are read by MariaDB server.
# Use it for options that only the server (but not clients) should see
#
# See the examples of server my.cnf files in /usr/share/mysql/
#

# this is read by the standalone daemon and embedded servers
[server]

# this is only for the mysqld standalone daemon
# Settings user and group are ignored when systemd is used.
# If you need to run mysqld under a different user or group,
# customize your systemd unit file for mysqld/mariadb according to the
# instructions in http://fedoraproject.org/wiki/Systemd
[mysqld]
server-id=2
read-only=OFF
log-bin                                                                                                     
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
log-error=/var/log/mariadb/mariadb.log
pid-file=/run/mariadb/mariadb.pid

[19:08:51 root@slave1 ~]#mysql

Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 19
Server version: 10.3.17-MariaDB MariaDB Server

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

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

MariaDB [(none)]> set global read_only=off; --关闭只读
Query OK, 0 rows affected (0.000 sec)

MariaDB [(none)]> stop slave; --停止从复制线程
Query OK, 0 rows affected (0.002 sec)

MariaDB [(none)]> reset slave all; --清空slave信息
Query OK, 0 rows affected (0.001 sec)

[19:24:11 root@slave1 ~]#systemctl restart mariadb #重启数据库
[19:24:20 root@slave1 ~]#mysqldump -A --single-transaction --master-data=1 -F > backup.sql #对数据库进行全量备份
[19:26:22 root@slave1 ~]#vi backup.sql  #修改备份中的change master to

-- MySQL dump 10.17  Distrib 10.3.17-MariaDB, for Linux (x86_64)
--
-- Host: localhost    Database: 
-- ------------------------------------------------------
-- Server version   10.3.17-MariaDB-log

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

--
-- Position to start replication or point-in-time recovery from
--

CHANGE MASTER TO 
MASTER_HOST='10.0.0.38',
MASTER_USER='repluser',
MASTER_PASSWORD='123456',                                                                                   
MASTER_LOG_FILE='mariadb-bin.000002', MASTER_LOG_POS=375;
...

[19:37:04 root@slave1 ~]#scp backup.sql 10.0.0.48:/root #将备份拷贝至其他从节点
The authenticity of host '10.0.0.48 (10.0.0.48)' can't be established.
ECDSA key fingerprint is SHA256:B4GojTG9L1h2MUkoY950+2OuTNePsXfMQMtcFn6Z3YE.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '10.0.0.48' (ECDSA) to the list of known hosts.
[email protected]'s password: 
backup.sql                                                                100%  477KB  44.8MB/s   00:00  

[19:42:44 root@slave2 ~]#mysql
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 9
Server version: 10.3.17-MariaDB-log MariaDB Server

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

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

MariaDB [(none)]> stop slave; --停止slave
Query OK, 0 rows affected, 1 warning (0.000 sec)

MariaDB [(none)]> reset slave all; --清空slave信息
Query OK, 0 rows affected (0.000 sec)

MariaDB [(none)]> set sql_log_bin=off; --关闭二进制日志
Query OK, 0 rows affected (0.000 sec)

MariaDB [(none)]> source backup.sql; --恢复数据库
Query OK, 0 rows affected (0.000 sec)

Query OK, 0 rows affected (0.000 sec)

Query OK, 0 rows affected (0.000 sec)

Query OK, 0 rows affected (0.000 sec)

....

MariaDB [mysql]> set sql_log_bin=on; --开启二进制日志
Query OK, 0 rows affected (0.000 sec)

MariaDB [mysql]> start slave; --开启slave线程
Query OK, 0 rows affected (0.002 sec)

3、通过 MHA 0.58 搭建一个数据库集群结构.

#在centos7上用yum安装mha的manager包和node包,yum可以自动解决依赖问题,manager包不支持centos8,所以需要安装在centos7上,node包支持mysql 5.7,不支持centos8上的mariadb 10.3.17,在centos8上安装node包
[19:13:38 root@localhost ~]#yum -y install mha4mysql-*.rpm 
Loaded plugins: fastestmirror
Examining mha4mysql-manager-0.58-0.el7.centos.noarch.rpm: mha4mysql-manager-0.58-0.el7.centos.noarch
Marking mha4mysql-manager-0.58-0.el7.centos.noarch.rpm to be installed
Examining mha4mysql-node-0.58-0.el7.centos.noarch.rpm: mha4mysql-node-0.58-0.el7.centos.noarch
Marking mha4mysql-node-0.58-0.el7.centos.noarch.rpm to be installed
Resolving Dependencies
--> Running transaction check
---> Package mha4mysql-manager.noarch 0:0.58-0.el7.centos will be installed
--> Processing Dependency: perl(Config::Tiny) for package: mha4mysql-manager-0.58-0.el7.centos.noarch
Determining fastest mirrors
 * base: mirrors.aliyun.com
 * extras: mirrors.aliyun.com
 * updates: mirrors.aliyun.com
base                                                                                 | 3.6 kB  00:00:00     
epel                                                                                 | 4.7 kB  00:00:00     
extras                                                                               | 2.9 kB  00:00:00     
updates                                                                              | 2.9 kB  00:00:00     
(1/5): epel/x86_64/updateinfo                                                        | 1.0 MB  00:00:00     
(2/5): epel/x86_64/primary_db                                                        | 6.9 MB  00:00:00     
(3/5): epel/x86_64/group_gz                                                          |  95 kB  00:00:06     
(4/5): extras/7/x86_64/primary_db                                                    | 206 kB  00:00:05     
(5/5): updates/7/x86_64/primary_db                                                   | 4.5 MB  00:00:05 
....

#利用脚本在centos7上安装mysql5.7,并利用yum安装mha的node包
--------------------------------------------------------------------------------------------------
#!/bin/bash
#
#********************************************************************
#Author:        wangxiaochun
#QQ:            29308620
#Date:          2020-02-12
#FileName:     install_mysql5.7_for_centos.sh
#URL:           http://www.magedu.com
#Description:      The test script
#Copyright (C):     2020 All rights reserved
#********************************************************************

. /etc/init.d/functions
SRC_DIR=`pwd`
MYSQL='mysql-5.7.29-linux-glibc2.12-x86_64.tar.gz'
COLOR='echo -e \E[01;31m'
END='\E[0m'
MYSQL_ROOT_PASSWORD=magedu


check (){

if [ $UID -ne 0 ]; then
  action "当前用户不是root,安装失败" false

cd  $SRC_DIR
if [ !  -e $MYSQL ];then
        $COLOR"缺少${MYSQL}文件"$END
        $COLOR"请将相关软件放在${SRC_DIR}目录下"$END
        exit
elif [ -e /usr/local/mysql ];then
        action "数据库已存在,安装失败" false
        exit
else
    return
fi
} 

install_mysql(){
    $COLOR"开始安装MySQL数据库..."$END
    yum  -y -q install libaio numactl-libs   libaio &> /dev/null
    cd $SRC_DIR
    tar xf $MYSQL -C /usr/local/
    MYSQL_DIR=`echo $MYSQL| sed -nr 's/^(.*[0-9]).*/\1/p'`
    ln -s  /usr/local/$MYSQL_DIR /usr/local/mysql
    chown -R  root.root /usr/local/mysql/
    id mysql &> /dev/null || { useradd -s /sbin/nologin -r  mysql ; action "创建mysql用户"; }
        
    echo 'PATH=/usr/local/mysql/bin/:$PATH' > /etc/profile.d/mysql.sh
    .  /etc/profile.d/mysql.sh
    ln -s /usr/local/mysql/bin/* /usr/bin/
    cat > /etc/my.cnf <<-EOF
[mysqld]
server-id=1
log-bin
datadir=/data/mysql
socket=/data/mysql/mysql.sock                                                                                                   
log-error=/data/mysql/mysql.log
pid-file=/data/mysql/mysql.pid
[client]
socket=/data/mysql/mysql.sock
EOF
    mysqld --initialize --user=mysql --datadir=/data/mysql 
    cp /usr/local/mysql/support-files/mysql.server  /etc/init.d/mysqld
    chkconfig --add mysqld
    chkconfig mysqld on
    service mysqld start
    [ $? -ne 0 ] && { $COLOR"数据库启动失败,退出!"$END;exit; }
    MYSQL_OLDPASSWORD=`awk '/A temporary password/{print $NF}' /data/mysql/mysql.log`
    mysqladmin  -uroot -p$MYSQL_OLDPASSWORD password $MYSQL_ROOT_PASSWORD &>/dev/null
    action "数据库安装完成" 
}


check

install_mysql 
-----------------------------------------------------------------------------------------------------------
[19:30:09 root@localhost ~]#yum -y install mha4mysql-node-0.58-0.el7.centos.noarch.rpm  #在所有数据库服务器上安装mha node包
Last metadata expiration check: 0:18:02 ago on Fri 16 Oct 2020 07:12:22 PM CST.
Dependencies resolved.
============================================================================================================
 Package                        Arch       Version                                   Repository        Size
============================================================================================================
Installing:
 mha4mysql-node                 noarch     0.58-0.el7.centos                         @commandline      35 k
Installing dependencies:
 mariadb-connector-c            x86_64     3.0.7-1.el8                               AppStream        148 k
 mariadb-connector-c-config     noarch     3.0.7-1.el8                               AppStream         13 k
 perl-Carp                      noarch     1.42-396.el8                              base              30 k
 perl-DBD-MySQL                 x86_64     4.046-3.module_el8.1.0+203+e45423dc       AppStream        156 k
 perl-DBI                       x86_64     1.641-3.module_el8.1.0+199+8f0a6bbd       AppStream        740 k
 perl-Data-Dumper               x86_64     2.167-399.el8                             base              58 k
 perl-Digest                    noarch     1.17-395.el8                              AppStream         27 k
 perl-Digest-MD5                x86_64     2.55-396.el8                              AppStream         37 k
 perl-Encode                    x86_64     4:2.97-3.el8                              base             1.5 M
 perl-Errno                     x86_64     1.28-416.el8                              base              76 k
 perl-Exporter                  noarch     5.72-396.el8                              base              34 k
 perl-File-Path                 noarch     2.15-2.el8                                base              38 k
 perl-File-Temp                 noarch     0.230.600-1.el8                           base              63 k
....

#实现所有节点基于key验证登录
[19:14:38 root@localhost ~]#ssh-keygen #生成公钥私钥对
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): 
Created directory '/root/.ssh'.
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:gjfZk4eqKMg9L2ugg8PU5rlLoO9Tm+rwnHugNKp0PmA [email protected]
The key's randomart image is:
+---[RSA 2048]----+
|                 |
|                 |
|                 |
|     . o o       |
| .. . = S .      |
|.Eoo.. + o       |
|&oB=.o.          |
|@B=@+.           |
|o*%XX.           |
+----[SHA256]-----+
[19:41:01 root@localhost ~]#ssh-copy-id 127.0.0.1
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
The authenticity of host '127.0.0.1 (127.0.0.1)' can't be established.
ECDSA key fingerprint is SHA256:SmW5yVWvmhKkkFt+09DAfo65BTAzFzAB1adthknSPOs.
ECDSA key fingerprint is MD5:94:ee:5c:d2:83:87:45:40:2c:f4:34:c9:1a:65:52:0c.
Are you sure you want to continue connecting (yes/no)? yes
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
[email protected]'s password: 

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh '127.0.0.1'"
and check to make sure that only the key(s) you wanted were added.
#所有主机公用一组公钥私钥对
[19:42:17 root@localhost ~]#rsync -a .ssh 10.0.0.8:/root/
The authenticity of host '10.0.0.8 (10.0.0.8)' can't be established.
ECDSA key fingerprint is SHA256:B4GojTG9L1h2MUkoY950+2OuTNePsXfMQMtcFn6Z3YE.
ECDSA key fingerprint is MD5:67:05:02:31:bc:fc:06:c5:a3:6e:77:49:d9:41:55:98.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '10.0.0.8' (ECDSA) to the list of known hosts.
[email protected]'s password: 
[19:42:49 root@localhost ~]#rsync -a .ssh 10.0.0.18:/root/
The authenticity of host '10.0.0.18 (10.0.0.18)' can't be established.
ECDSA key fingerprint is SHA256:B4GojTG9L1h2MUkoY950+2OuTNePsXfMQMtcFn6Z3YE.
ECDSA key fingerprint is MD5:67:05:02:31:bc:fc:06:c5:a3:6e:77:49:d9:41:55:98.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '10.0.0.18' (ECDSA) to the list of known hosts.
[email protected]'s password: 
[19:42:56 root@localhost ~]#rsync -a .ssh 10.0.0.28:/root/
The authenticity of host '10.0.0.28 (10.0.0.28)' can't be established.
ECDSA key fingerprint is SHA256:B4GojTG9L1h2MUkoY950+2OuTNePsXfMQMtcFn6Z3YE.
ECDSA key fingerprint is MD5:67:05:02:31:bc:fc:06:c5:a3:6e:77:49:d9:41:55:98.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '10.0.0.28' (ECDSA) to the list of known hosts.
[email protected]'s password: 

#在管理节点创建配置文件
[19:46:02 root@localhost ~]#mkdir /etc/mastermha
[20:04:17 root@localhost ~]#vi /etc/mastermha/app1.cnf

[server default]
user=mhauser #用于远程链接MySQL所有节点的用户,需要有管理员权限
password=123456
manager_workdir=/data/mastermha/app1/  #该目录会自动生成
manager_log=/data/mastermha/app1/manager.log
remote_workdir=/data/mastermha/app1/
ssh_user=root   #用于实现远程ssh基于key验证的连接
repl_user=repluser #主从复制的用户
repl_password=123456
ping_interval=1 #健康检查的时间间隔
master_ip_failover_script=/usr/local/bin/master_ip_failover #切换VIP的perl脚本
report_script=/usr/local/bin/sendmail.sh #报警脚本
check_repl_delay=0 #默认slave中从库落后主库relaylog超过100M,主库不会选择这个从库为新的master,因为这个从库>进行恢复需要很长的时间。通过这个参数,mha触发主从切换的时候会忽略复制的延时,对于设置candidate_master=1的从>库非常有用,确保这个从库一定能成为最新的master
master_binlog_dir=/data/mysql/ #指定二进制日志存放的目录,mha4mysql-manager-0.58版本必须指定,之前的不需要

[server1]
hostname=10.0.0.8
candidate_master=1
[server2]
hostname=10.0.0.18
candidate_master=1 #设置优先候选master,即使不是集群中事件最新的从节点也会当选master
[server3]
hostname=10.0.0.28      

#发送邮件需要需要配置.mailrc和安装mailx
[20:57:50 root@localhost ~]#cat .mail.rc 
set [email protected]
set smtp=smtp.qq.com
set [email protected]
set smtp-auth-password=***************  
set smtp-auth=login
set ssl-verify=ignore

[21:01:11 root@localhost ~]#cat /usr/local/bin/sendmail.sh  
#!/bin/bash
#
#********************************************************************
#Author:            rzx
#QQ:                970707452
#Date:              2020-10-16
#FileName:         /usr/local/bin/sendmail.sh
#URL:               https://www.cnblogs.com/rzx-006/
#Description:      The test script
#Copyright (C):    2020 All rights reserved
#********************************************************************
echo "Mysql is down !" | mail -s "MHA Warning" [email protected]

[21:01:17 root@localhost ~]#chmod +x /usr/local/bin/sendmail.sh  #为右键发送脚本添加执行权限

[21:30:55 root@localhost ~]#cat /usr/local/bin/master_ip_failover  #切换vip的perl脚本
#!/usr/bin/env perl
use strict;
use warnings FATAL=> 'all';
use Getopt::Long;
my(
$command, $ssh_user, $orig_master_host, $orig_master_ip, $orig_master_port,$new_master_host, $new_master_ip, $new_master_port);
my $vip = '10.0.0.100/24';
my $gateway = '10.0.0.2';
my $interface = 'eth0';
my $key = "1";
my $ssh_start_vip = "/sbin/ifconfig $interface:$key $vip;/sbin/arping -I $interface -c 3 -s $vip $gateway > /dev/null 2&>1";
my $ssh_stop_vip = "/sbin/ifconfig $interface:$key down";
GetOptions(
'command=s' => \$command,
'ssh_user=s' => \$ssh_user,
'orig_master_host=s' => \$orig_master_host,
'orig_master_ip=s' => \$orig_master_ip,
'orig_master_port=i' => \$orig_master_port,
'new_master_host=s' => \$new_master_host,
'new_master_ip=s' => \$new_master_ip,
'new_master_port=i' => \$new_master_port,
);
exit &main();
sub main {
print "\n\nIN SCRIPT TEST====$ssh_stop_vip==$ssh_start_vip===\n\n";
if ( $command eq "stop" || $command eq "stopssh" ) {
# $orig_master_host,$orig_master_ip,$orig_master_port are passed.
# If you manage master ip address at global catalog database,
# invalidate orig_master_ip here.
my $exit_code = 1;
eval {
print "Disabling the VIP on old master: $orig_master_host \n";
$exit_code = 0;
};
if ($@) {
warn "Got Error: $@\n";
exit $exit_code;
}
exit $exit_code;
}
elsif ( $command eq "start" ) {
# all arguments are passed.
# If you manage master ip address at global catalog database,
# activate new_master_ip here,
# You can also grant write access (create user, set read_only=0, etc) here.
my $exit_code = 10;
eval {
print "Enabling the VIP - $vip on the new master - $new_master_host \n";
&start_vip();
$exit_code = 0;
};
if ($@) {
warn $@;
exit $exit_code;
}
exit $exit_code;
}
elsif ( $command eq "status" ) {
print "Checking the Status of the script.. OK \n";
`ssh $ssh_user\@$orig_master_host \" $ssh_start_vip \"`;
exit 0;
}
else {
&usage();
exit 1;
}
}
# A simple system call that enable the VIP on the new master
sub start_vip() {
`ssh $ssh_user\@$new_master_host \" $ssh_start_vip \"`;
}
# A simple system call that disable the VIP on the old master
sub stop_vip() {
`ssh $ssh_user\@$orig_master_host \" $ssh_stop_vip \"`;
}
sub usage {
print
"Usage: master_ip_failover --command=start|stop|stopssh|status --orig_master_host=host --orig_master_ip=ip --orig_master_port=port --new_master_host=host --new_master_ip=ip --new_master_port=port\n";
}
  
#实现master节点
[21:32:45 root@localhost ~]#vi /etc/my.cnf

[mysqld]
server-id=1
datadir=/data/mysql
log-bin=/data/mysql/mysql-bin
skip_name_resolve=1  #禁止反向解析
general_log
socket=/data/mysql/mysql.sock 
log-error=/data/mysql/mysql.log
pid-file=/data/mysql/mysql.pid
[client]
socket=/data/mysql/mysql.sock

[21:35:03 root@localhost ~]#mysql -uroot -pmagedu
                   
--记录二进制日志位置,创建复制所需账号,创建mha所需账号
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.29-log MySQL Community Server (GPL)

Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.

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> show master logs;
+------------------+-----------+
| Log_name         | File_size |
+------------------+-----------+
| mysql-bin.000001 |       154 |
+------------------+-----------+
1 row in set (0.00 sec)

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

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

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.29-log MySQL Community Server (GPL)

Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.

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='10.0.0.8', 
    -> MASTER_USER='repluser',
    -> MASTER_PASSWORD='123456', 
    -> MASTER_LOG_FILE='mysql-bin.000001', 
    -> MASTER_LOG_POS=154;
Query OK, 0 rows affected, 2 warnings (0.00 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: 10.0.0.8
                  Master_User: repluser
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-bin.000002
          Read_Master_Log_Pos: 154
               Relay_Log_File: localhost-relay-bin.000003
                Relay_Log_Pos: 367
        Relay_Master_Log_File: mysql-bin.000002
             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: 1539
              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: 1
                  Master_UUID: cf72a786-0ee3-11eb-acb3-000c29f125ee
             Master_Info_File: /data/mysql/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)
#实现slave节点2
[21:47:43 root@localhost ~]#vi /etc/my.cnf

[mysqld]
server-id=3                                                                                                 
log-bin=/data/mysql/mysql-bin
read_only
relay_log_purge=0
skip_name_resolve=1 #禁止反向解析
datadir=/data/mysql
socket=/data/mysql/mysql.sock
log-error=/data/mysql/mysql.log
pid-file=/data/mysql/mysql.pid
[client]
socket=/data/mysql/mysql.sock

[21:48:05 root@localhost ~]#mysql -uroot -pmagedu
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.29-log MySQL Community Server (GPL)

Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.

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='10.0.0.8', 
    -> MASTER_USER='repluser',
    -> MASTER_PASSWORD='123456', 
    -> MASTER_LOG_FILE='mysql-bin.000001', 
    -> MASTER_LOG_POS=154;
Query OK, 0 rows affected, 2 warnings (0.01 sec)

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

mysql> show slave status\G
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 10.0.0.8
                  Master_User: repluser
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-bin.000002
          Read_Master_Log_Pos: 154
               Relay_Log_File: localhost-relay-bin.000003
                Relay_Log_Pos: 367
        Relay_Master_Log_File: mysql-bin.000002
             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: 1539
              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: 1
                  Master_UUID: cf72a786-0ee3-11eb-acb3-000c29f125ee
             Master_Info_File: /data/mysql/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: [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.29-log MySQL Community Server (GPL)

Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.

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='10.0.0.8', 
    -> MASTER_USER='repluser',
    -> MASTER_PASSWORD='123456', 
    -> MASTER_LOG_FILE='mysql-bin.000001', 
    -> MASTER_LOG_POS=154;
Query OK, 0 rows affected, 2 warnings (0.01 sec)

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

mysql> show slave status\G
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 10.0.0.8
                  Master_User: repluser
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-bin.000002
          Read_Master_Log_Pos: 154
               Relay_Log_File: localhost-relay-bin.000003
                Relay_Log_Pos: 367
        Relay_Master_Log_File: mysql-bin.000002
             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: 1539
              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: 1
                  Master_UUID: cf72a786-0ee3-11eb-acb3-000c29f125ee
             Master_Info_File: /data/mysql/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)

4、实战案例:Percona XtraDB Cluster(PXC 5.7)

[15:10:41 root@manager ~]#vi /etc/yum.repos.d/pxc.repo  #配置pxc的yum源

[percona]
name=percona_repo
baseurl = https://mirrors.tuna.tsinghua.edu.cn/percona/release/$releasever/RPMS/$basearch
enabled = 1
gpgcheck = 0 
[15:12:47 root@manager ~]#scp /etc/yum.repos.d/pxc.repo 10.0.0.17:/etc/yum.repos.d/ #将yum仓库文件传到另外两个节点
The authenticity of host '10.0.0.17 (10.0.0.17)' can't be established.
ECDSA key fingerprint is SHA256:SmW5yVWvmhKkkFt+09DAfo65BTAzFzAB1adthknSPOs.
ECDSA key fingerprint is MD5:94:ee:5c:d2:83:87:45:40:2c:f4:34:c9:1a:65:52:0c.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '10.0.0.17' (ECDSA) to the list of known hosts.
[email protected]'s password: 
pxc.repo                                                                  100%  143   190.2KB/s   00:00    
[15:13:19 root@manager ~]#scp /etc/yum.repos.d/pxc.repo 10.0.0.27:/etc/yum.repos.d/
The authenticity of host '10.0.0.27 (10.0.0.27)' can't be established.
ECDSA key fingerprint is SHA256:SmW5yVWvmhKkkFt+09DAfo65BTAzFzAB1adthknSPOs.
ECDSA key fingerprint is MD5:94:ee:5c:d2:83:87:45:40:2c:f4:34:c9:1a:65:52:0c.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '10.0.0.27' (ECDSA) to the list of known hosts.
[email protected]'s password: 
pxc.repo                                                                  100%  143   162.8KB/s   00:00 


[15:18:05 root@pxc1 ~]#yum install -y Percona-XtraDB-Cluster-57 #在所有节点安装pxc软件包
.....
Dependency Installed:
  Percona-XtraDB-Cluster-client-57.x86_64 0:5.7.31-31.45.1.el7                                              
  Percona-XtraDB-Cluster-server-57.x86_64 0:5.7.31-31.45.1.el7                                              
  libaio.x86_64 0:0.3.109-13.el7                                                                            
  libev.x86_64 0:4.15-7.el7                                                                                 
  lsof.x86_64 0:4.87-6.el7                                                                                  
  percona-xtrabackup-24.x86_64 0:2.4.20-1.el7                                                               
  perl-Compress-Raw-Bzip2.x86_64 0:2.061-3.el7                                                              
  perl-Compress-Raw-Zlib.x86_64 1:2.061-4.el7                                                               
  perl-DBD-MySQL.x86_64 0:4.023-6.el7                                                                       
  perl-DBI.x86_64 0:1.627-4.el7                                                                             
  perl-Data-Dumper.x86_64 0:2.145-3.el7                                                                     
  perl-Digest.noarch 0:1.17-245.el7                                                                         
  perl-Digest-MD5.x86_64 0:2.52-3.el7                                                                       
  perl-IO-Compress.noarch 0:2.061-2.el7                                                                     
  perl-Net-Daemon.noarch 0:0.48-5.el7                                                                       
  perl-PlRPC.noarch 0:0.2020-14.el7                                                                         
  qpress.x86_64 0:11-1.el7                                                                                  
  socat.x86_64 0:1.7.3.2-2.el7                                                                              

Replaced:
  mariadb-libs.x86_64 1:5.5.65-1.el7                                                                        

Complete!
[15:46:07 root@pxc2 ~]#vi /etc/percona-xtradb-cluster.conf.d/mysqld.cnf #修改节点的serverid 

# Template my.cnf for PXC
# Edit to your requirements.
[client]
socket=/var/lib/mysql/mysql.sock

[mysqld]
server-id=2                                                                                                 
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid
log-bin
log_slave_updates
expire_logs_days=7

# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0

[15:46:53 root@pxc3 ~]#vi /etc/percona-xtradb-cluster.conf.d/mysqld.cnf

# Template my.cnf for PXC
# Edit to your requirements.
[client]
socket=/var/lib/mysql/mysql.sock

[mysqld]
server-id=3                                                                                                 
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid
log-bin
log_slave_updates
expire_logs_days=7

# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0

[15:45:51 root@pxc1 ~]#vi /etc/percona-xtradb-cluster.conf.d/wsrep.cnf 

[mysqld]
# Path to Galera library
wsrep_provider=/usr/lib64/galera3/libgalera_smm.so

# Cluster connection URL contains IPs of nodes
#If no IP is found, this implies that a new cluster needs to be created,
#in order to do that you need to bootstrap this node
wsrep_cluster_address=gcomm://10.0.0.7,10.0.0.17,10.0.0.27 #填写所有pxc节点的ip

# In order for Galera to work correctly binlog format should be ROW
binlog_format=ROW

# MyISAM storage engine has only experimental support
default_storage_engine=InnoDB

# Slave thread to use
wsrep_slave_threads= 8

wsrep_log_conflicts

# This changes how InnoDB autoincrement locks are managed and is a requirement for Galera
innodb_autoinc_lock_mode=2

# Node IP address
wsrep_node_address=10.0.0.7 #填写本节点的ip
# Cluster name
wsrep_cluster_name=pxc-cluster

#If wsrep_node_name is not specified,  then system hostname will be used
wsrep_node_name=pxc-cluster-node-1  #节点编号,各个节点需要不一致

#pxc_strict_mode allowed values: DISABLED,PERMISSIVE,ENFORCING,MASTER
pxc_strict_mode=ENFORCING

# SST method
wsrep_sst_method=xtrabackup-v2

#Authentication for SST method
wsrep_sst_auth="sstuser:s3cretPass"  #取消此行注释

[15:46:38 root@pxc2 ~]#vi /etc/percona-xtradb-cluster.conf.d/wsrep.cnf 

[mysqld]
# Path to Galera library
wsrep_provider=/usr/lib64/galera3/libgalera_smm.so

# Cluster connection URL contains IPs of nodes
#If no IP is found, this implies that a new cluster needs to be created,
#in order to do that you need to bootstrap this node
wsrep_cluster_address=gcomm://10.0.0.7,10.0.0.17,10.0.0.27

# In order for Galera to work correctly binlog format should be ROW
binlog_format=ROW

# MyISAM storage engine has only experimental support
default_storage_engine=InnoDB

# Slave thread to use
wsrep_slave_threads= 8

wsrep_log_conflicts

# This changes how InnoDB autoincrement locks are managed and is a requirement for Galera
innodb_autoinc_lock_mode=2

# Node IP address
wsrep_node_address=10.0.0.17
# Cluster name
wsrep_cluster_name=pxc-cluster

#If wsrep_node_name is not specified,  then system hostname will be used
wsrep_node_name=pxc-cluster-node-2

#pxc_strict_mode allowed values: DISABLED,PERMISSIVE,ENFORCING,MASTER
pxc_strict_mode=ENFORCING

# SST method
wsrep_sst_method=xtrabackup-v2

#Authentication for SST method
wsrep_sst_auth="sstuser:s3cretPass" 

[15:48:31 root@pxc3 ~]#vi /etc/percona-xtradb-cluster.conf.d/wsrep.cnf 

[mysqld]
# Path to Galera library
wsrep_provider=/usr/lib64/galera3/libgalera_smm.so

# Cluster connection URL contains IPs of nodes
#If no IP is found, this implies that a new cluster needs to be created,
#in order to do that you need to bootstrap this node
wsrep_cluster_address=gcomm://10.0.0.7,10.0.0.17,10.0.0.27

# In order for Galera to work correctly binlog format should be ROW
binlog_format=ROW

# MyISAM storage engine has only experimental support
default_storage_engine=InnoDB

# Slave thread to use
wsrep_slave_threads= 8

wsrep_log_conflicts

# This changes how InnoDB autoincrement locks are managed and is a requirement for Galera
innodb_autoinc_lock_mode=2

# Node IP address
wsrep_node_address=10.0.0.27
# Cluster name
wsrep_cluster_name=pxc-cluster

#If wsrep_node_name is not specified,  then system hostname will be used
wsrep_node_name=pxc-cluster-node-3

#pxc_strict_mode allowed values: DISABLED,PERMISSIVE,ENFORCING,MASTER
pxc_strict_mode=ENFORCING

# SST method
wsrep_sst_method=xtrabackup-v2

#Authentication for SST method
wsrep_sst_auth="sstuser:s3cretPass"


[15:58:56 root@pxc1 ~]#systemctl start [email protected] #启动集群中第一个节点

[16:01:07 root@pxc1 ~]#grep  "temporary password" /var/log/mysqld.log  #查看数据库默认密码
2020-10-17T07:59:47.273274Z 1 [Note] A temporary password is generated for root@localhost: ovLTp2jHyu?V

[16:01:23 root@pxc1 ~]#mysql -uroot -povLTp2jHyu?V #登录数据库

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 11
Server version: 5.7.31-34-57-log

Copyright (c) 2009-2020 Percona LLC and/or its affiliates
Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.

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> alter user 'root'@'localhost' identified by '123456'; --修改数据库root用户密码
Query OK, 0 rows affected (0.01 sec)

mysql> create user 'sstuser'@'localhost' identified by 's3cretPass'; --创建sstuser账号并授权
Query OK, 0 rows affected (0.01 sec)

mysql> GRANT RELOAD, LOCK TABLES, PROCESS, REPLICATION CLIENT ON *.* TO 'sstuser'@'localhost';
Query OK, 0 rows affected (0.00 sec)

mysql> show status like 'wsrep%';
+----------------------------------+--------------------------------------+
| Variable_name                    | Value                                |
+----------------------------------+--------------------------------------+
| wsrep_local_state_uuid           | bf07ae2c-104e-11eb-bf7f-53da762cf8f0 |
| wsrep_protocol_version           | 9                                    |
| wsrep_last_applied               | 3                                    |
| wsrep_last_committed             | 3                                    |
| wsrep_replicated                 | 3                                    |
| wsrep_replicated_bytes           | 760                                  |
| wsrep_repl_keys                  | 3                                    |
| wsrep_repl_keys_bytes            | 96                                   |
| wsrep_repl_data_bytes            | 463                                  |
| wsrep_repl_other_bytes           | 0                                    |
| wsrep_received                   | 2                                    |
| wsrep_received_bytes             | 150                                  |
| wsrep_local_commits              | 0                                    |
| wsrep_local_cert_failures        | 0                                    |
| wsrep_local_replays              | 0                                    |
| wsrep_local_send_queue           | 0                                    |
| wsrep_local_send_queue_max       | 1                                    |
| wsrep_local_send_queue_min       | 0                                    |
| wsrep_local_send_queue_avg       | 0.000000                             |
| wsrep_local_recv_queue           | 0                                    |
| wsrep_local_recv_queue_max       | 2                                    |
| wsrep_local_recv_queue_min       | 0                                    |
| wsrep_local_recv_queue_avg       | 0.500000                             |
| wsrep_local_cached_downto        | 1                                    |
| wsrep_flow_control_paused_ns     | 0                                    |
| wsrep_flow_control_paused        | 0.000000                             |
| wsrep_flow_control_sent          | 0                                    |
| wsrep_flow_control_recv          | 0                                    |
| wsrep_flow_control_interval      | [ 100, 100 ]                         |
| wsrep_flow_control_interval_low  | 100                                  |
| wsrep_flow_control_interval_high | 100                                  |
| wsrep_flow_control_status        | OFF                                  |
| wsrep_cert_deps_distance         | 1.000000                             |
| wsrep_apply_oooe                 | 0.000000                             |
| wsrep_apply_oool                 | 0.000000                             |
| wsrep_apply_window               | 1.000000                             |
| wsrep_commit_oooe                | 0.000000                             |
| wsrep_commit_oool                | 0.000000                             |
| wsrep_commit_window              | 1.000000                             |
| wsrep_local_state                | 4                                    | 
| wsrep_local_state_comment        | Synced                               | --状态为Synced(4),表示数据已同步完成(因为是第一个引导节点,无数                                                                            	   据需要同步)。 如果状态是Joiner, 意味着 SST 没有完成. 只有所有节点																	    状态是Synced,才可以加新节点
| wsrep_cert_index_size            | 1                                    | 
| wsrep_cert_bucket_count          | 22                                   |
| wsrep_gcache_pool_size           | 2200                                 |
| wsrep_causal_reads               | 0                                    |
| wsrep_cert_interval              | 0.000000                             |
| wsrep_open_transactions          | 0                                    |
| wsrep_open_connections           | 0                                    |
| wsrep_ist_receive_status         |                                      |
| wsrep_ist_receive_seqno_start    | 0                                    |
| wsrep_ist_receive_seqno_current  | 0                                    |
| wsrep_ist_receive_seqno_end      | 0                                    |
| wsrep_incoming_addresses         | 10.0.0.7:3306                        |
| wsrep_cluster_weight             | 1                                    |
| wsrep_desync_count               | 0                                    |
| wsrep_evs_delayed                |                                      |
| wsrep_evs_evict_list             |                                      |
| wsrep_evs_repl_latency           | 0/0/0/0/0                            |
| wsrep_evs_state                  | OPERATIONAL                          |
| wsrep_gcomm_uuid                 | bf06bab9-104e-11eb-a246-fb02fcb94060 |
| wsrep_cluster_conf_id            | 1                                    |
| wsrep_cluster_size               | 1                                    | --表示集群中在线的节点
| wsrep_cluster_state_uuid         | bf07ae2c-104e-11eb-bf7f-53da762cf8f0 |
| wsrep_cluster_status             | Primary                              | --表示节点已经完全连接并准备好
| wsrep_connected                  | ON                                   |
| wsrep_local_bf_aborts            | 0                                    |
| wsrep_local_index                | 0                                    |
| wsrep_provider_name              | Galera                               |
| wsrep_provider_vendor            | Codership Oy     |
| wsrep_provider_version           | 3.45(ra60e019)                       |
| wsrep_ready                      | ON                                   |
+----------------------------------+--------------------------------------+
71 rows in set (0.00 sec)

#启动其他节点
[16:13:18 root@pxc3 ~]#mysql -uroot -p123456

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 11
Server version: 5.7.31-34-57-log Percona XtraDB Cluster (GPL), Release rel34, Revision 7359e4f, WSREP version 31.45, wsrep_31.45

Copyright (c) 2009-2020 Percona LLC and/or its affiliates
Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.

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> show VARIABLES like 'wsrep_node_name'; --在任意节点查看集群的状态
+-----------------+--------------------+
| Variable_name   | Value              |
+-----------------+--------------------+
| wsrep_node_name | pxc-cluster-node-3 |
+-----------------+--------------------+
1 row in set (0.00 sec)

mysql> show status like 'wsrep_cluster_size';
+--------------------+-------+
| Variable_name      | Value |
+--------------------+-------+
| wsrep_cluster_size | 3     |
+--------------------+-------+
1 row in set (0.00 sec)

mysql> create database test; --在任意节点创建数据库
Query OK, 1 row affected (0.00 sec)

mysql> show databases; --在其他节点查看数据库
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
| test               |
+--------------------+
5 rows in set (0.01 sec)

5、通过 ansible 部署二进制 mysql 8.0

[15:11:32 root@localhost ~]#vi mysql8.0_install.yml 

---
- hosts: dbsrv                                                                                                                                                                                                                                    
  remote_user: root
  gather_facts: no

  tasks:
    - name: add group mysql
      group: name=mysql state=present
    - name: add user mysql
      user: name=mysql state=present group=mysql
    - name: Install packeges
      yum: name=libaio,numactl-libs,libaio,ncurses-compat-libs
    - name: decompression
      unarchive: src=/root/mysql-8.0.21-linux-glibc2.12-x86_64.tar.xz dest=/usr/local
    - name: create symbolic link
      file: src=/usr/local/mysql-8.0.21-linux-glibc2.12-x86_64 dest=/usr/local/mysql state=link
    - name: modify path
      shell: echo 'PATH=/usr/local/mysql/bin/:$PATH' > /etc/profile.d/mysql.sh
    - name: modify path
      shell: source /etc/profile.d/mysql.sh
    - name: create my.cnf
      shell: echo -e '[mysqld]\nserver-id=1\nlog-bin\ndatadir=/data/mysql\nsocket=/data/mysql/mysql.sock\nlog-error=/data/mysql/mysql.log\npid-file=/data/mysql/mysql.pid\n[client]\nsocket=/data/mysql/mysql.sock'> /etc/my.cnf
    - name: install mysql
      shell: mysqld --initialize-insecure --user=mysql --datadir=/data/mysql
    - name: creat mysqld
      shell: cp /usr/local/mysql/support-files/mysql.server  /etc/init.d/mysqld
    - name: set auto run
      shell: chkconfig --add mysqld
    - name: start mysql
      service: name=mysqld state=started
    - name: modify password
      shell: mysql -e "alter user root@localhost identified by '123456'"

你可能感兴趣的:(作业,mysql,centos,linux)