MySQL使用mysqldump備份及還原


  MySQL可以使用mysqldump進行數據的邏輯備份,配合開啟bin log日志可以實現數據的全量恢復及增量恢復

  MySQL版本查看

  修改配置文件記錄bin log日志

[mysqld]
#bin log日志記錄位置
log-bin=/opt/mysqldata/prodda3306data/mysql-bin
binlog_cache_size = 4M
max_binlog_cache_size = 256M
max_binlog_size = 32M
#日志模式為row 生產環境最好使用此日志模式
binlog_format = row
expire_logs_days = 7

  登錄MySQL終端查看日志模式

show variables like "binlog_format";

  查看bin log日志的POS值

show master status;

  制定備份腳本每日定時備份,把該腳本運行定時任務每日凌晨全備並且在備份是時候記錄bin log的POS位置值

#!/bin/bash
source /etc/profile
#mysqldump to fully backup mysql data
port=$1
password='password'
if [ $# -ne 1 ];then
echo "Usage: sh all.sh (3306|3307)"
exit 1
fi
psocket=`ps -ef|grep $port|grep "socket"|awk -vRS="--socket" '{t=$0;}END{print "--socket"t}'|awk '{print $1}'`
if [ -f /root/.bash_profile ];then
source /root/.bash_profile
fi
#定義備份目錄
BakDir=/opt/mysqlbak/full${port}
[ ! -d $BakDir ] && mkdir -p $BakDir
LogFile=$BakDir/bak.log
Date=`date +%Y%m%d`
Begin=`date +"%Y年%m月%d日 %H:%M:%S"`
cd $BakDir
DumpFile=$Date.sql
GZDumpFile=$Date.sql.tgz
mysqldump -uroot -p"$password" --all-databases --lock-all-tables --routines --triggers --events --master-data=2 --flush-logs $psocket --set-gtid-purged=OFF > $DumpFile
tar zcvf $GZDumpFile $DumpFile
if [ -f $DumpFile ];then
rm -rf $DumpFile
fi
Last=`date +"%Y年%m月%d日 %H:%M:%S"`
echo 開始:$Begin 結束:$Last $GZDumpFile succ >> $LogFile
sleep 1
#刪除超過10天的全備文件
find $BakDir -name "*.tgz" -mtime +10 -exec rm -rf {} \;

 

  恢復

   全備恢復,把備份文件解壓縮,把解壓后的文件打開查看POS值(在22行左右)

  使用全備進行全量恢復,恢復前需管理前端應用已避免數據混亂

 mysql -uroot -p123456 -h127.0.0.1 < 20190117.sql

  使用bin log進行增量恢復,為測試恢復效果在master主機上面新建數據庫及表

create database test;
use test
create table test(id int);
insert into test values(1);
select * from test;

  創建一個test庫和test表,並且往表里面插入一條數據

  把mysql-bin.001446及以后的日志(如果有的話)都拷貝下來

  使用mysqlbinlog命令還原日志,對於001446需要指定start position值,其他001446以后的日志(如果有的話)還原不需要指定start position值

mysqlbinlog mysql-bin.001446 --start-position=194 > 20190117binlog.sql

  還原

mysql -uroot -p123456 -h127.0.0.1 < 20190117binlog.sql

  查看是否還原

  全量及增量備份恢復成功

   PS:如果想針對單庫進行增量恢復可以在mysqbinlog到處的時候加參數-d 例如

mysqlbinlog -d test mysql-bin.001446

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM