主库IP:192.168.8.129 hostname:master
从库IP:192.168.8.130 hostname:slave
1、说明:此脚本针对上一篇文章《CentOS7.X安装部署mysql5.7主从环境》搭建完成后的主从随时同步使用https://blog.51cto.com/8355320/2448056
2、MySQL主从同步会出现如网络延迟等多种原因,造成主从环境不同步,当需要重新同步主从环境时,需要等到业务不繁忙的晚上或周末来进行,而使用脚本备份,有了全库备份,有了binlog日志偏移记录值,我们就可以实现随时进行主从同步操作
3、主库备份脚本:


[root@master]# cat /data/script/auto_mysql_masterbak.sh

#!/bin/bash
#Author Danrtsey
#function: 主库备份所有库,并记录master status,用于做主从同步恢复时使用
BACKUP_FOLDERNAME=/data/masterbak
DB_USERNAME="root"
DB_PASSWORD="密码"

LOG_FILE=${BACKUPFOLDERNAME}/mysqllogsdate +%F.log
DATA_FILE=${BACKUP_FOLDERNAME}/mysqlbackupdate +%F.sql.gz

MYSQL_CMD="/bin/mysql -u$DB_USERNAME -p$DB_PASSWORD"
MYSQL_DUMP="/bin/mysqldump --set-gtid-purged=off -u$DB_USERNAME -p$DB_PASSWORD -A -B --flush-logs --single-transaction -e"

#锁表--全库备份--查看主库状态并记录--解琐表
$MYSQL_CMD -e "flush tables with read lock;"
echo "-----show master status result-----" >>$LOG_FILE
$MYSQL_CMD -e "show master status;" >>$LOG_FILE
${MYSQL_DUMP} | gzip > $DATA_FILE
$MYSQL_CMD -e "unlock tables;"
#保留2份备份文件
find ${BACKUP_FOLDERNAME} -mtime +2 -name ".sql.gz" -exec rm -rf {} \;
find ${BACKUP_FOLDERNAME} -mtime +2 -name "
.log" -exec rm -rf {} \;

添加定时任务
[root@master]# crontab -l
30 01 * /data/script/auto_mysql_masterbak.sh

4、从库同步脚本
取主库数据库备份文件与日志文件,到从库还原同步
[root@slave]# cat /data/script/auto_mysql_slavebak.sh
#!/bin/bash
#Author Danrtsey
#function: 从库使用主库/data/masterbak的备份
#查看/data/masterbak下面的mysqllogs记录的主库master status信息
#从库同步时填写相关信息,实现从库随时同步使用

#注意更改MASTER_LOG_FILE对应的数值及MASTER_LOG_POS的数值,举例如下
#MASTER_LOG_FILE='mysql-bin.000002',
#MASTER_LOG_POS=342;

BACKUP_FOLDERNAME=/data/slavebak
DB_USERNAME="root"
DB_PASSWORD="密码"

LOG_FILE=${BACKUPFOLDERNAME}/mysqllogsdate +%F.log
DATA_FILE=${BACKUP_FOLDERNAME}/mysqlbackupdate +%F.sql.gz

MYSQL_CMD="/bin/mysql -u$DB_USERNAME -p$DB_PASSWORD"

#recover
cd ${BACKUP_FOLDERNAME}
gzip -d mysqlbackupdate +%F.sql.gz
$MYSQL_CMD < mysqlbackupdate +%F.sql

$MYSQL_CMD -e "stop slave;"
#config slave
$MYSQL_CMD -e "CHANGE MASTER TO MASTER_HOST='192.168.8.129',MASTER_PORT=3306,MASTER_USER='slave',MASTER_PASSWORD='密码',MASTER_LOG_FILE='mysql-bin.000002',MASTER_LOG_POS=342;"

$MYSQL_CMD -e "start slave;"
$MYSQL_CMD -e "show slave status\G"|egrep "IO_Running|SQL_Running" >$LOG_FILE
cat $LOG_FILE


从库同步时,查看日志显示有两个yes表示从库同步成功