MySQL 二进制日志备份

MySQL 中很少提及日志的备份,但日志备份也是非常重要,可以恢复到指定时间点。日志备份可以使用自带的工具 mysqlbinlog 进行备份,mysqlbinlog 也是解析 binlog 的工具。

相关参考: Using mysqlbinlog to Back Up Binary Log Files

 

示例:

# 备份指定 binlog 文件(备份的文件名有前缀 "prefix_"). 如备份文件 mysql-bin.000011
mysqlbinlog --host=localhost --port=3306 --user=root --password=mysql \
--raw --read-from-remote-server mysql-bin.000011 --result-file=/home/git/binlog/prefix_

# 备份指定 binlog 文件(无前缀只指定目标路径). 如备份文件 mysql-bin.000009 和 mysql-bin.000011
mysqlbinlog --host=localhost --port=3306 --user=root --password=mysql \
--raw --read-from-remote-server mysql-bin.000009 mysql-bin.000011 --result-file=/home/git/binlog/

# 备份到最新的 binlog 日志后停止. 从文件 mysql-bin.000010 开始备份到最后
mysqlbinlog --host=localhost --port=3306 --user=root --password=mysql \
--raw --read-from-remote-server --to-last-log mysql-bin.000010 --result-file=/home/git/binlog/

# 持续备份 binlog 日志. 从文件 mysql-bin.000010 开始备份到最后
mysqlbinlog --host=localhost --port=3306 --user=root --password=mysql \
--raw --read-from-remote-server --stop-never mysql-bin.000010 --result-file=/home/git/binlog/

 

备份脚本:

#!/bin/bash
# Author: huangzecheng
# nohup /opt/mysql_backup/mysql_binlog_sync_backup.sh > /dev/null 2>&1 &
# nohup /opt/mysql_backup/mysql_binlog_sync_backup.sh >> /opt/mysql_backup/logs/sync_binlog.log 2>&1 &

echo "The current pid is $$"
kill -9 `ps -aef | grep $(basename $0) | awk '{print $2}' | grep -v $$`
#kill -9 `ps -aef | grep mysql_binlog_sync_backup.sh | awk '{print $2}' | grep -v $$`

MYSQL_HOST=localhost
MYSQL_PORT=3306
MYSQL_USER="root"
MYSQL_PASS="mysql"
SLEEP_RECONN=30
BACKUP_DIR=/opt/mysql_backup/binlog/
MYSQL_OPTIONS="--host=${MYSQL_HOST} --port=${MYSQL_PORT} --user=${MYSQL_USER} --password=${MYSQL_PASS}"

while :
do
echo "`date +'%F %T'` Getting the latest binlog filename."

LOGBIN_INDEX=$(mysql $MYSQL_OPTIONS -se "SHOW VARIABLES WHERE VARIABLE_NAME = 'log_bin_index';" 2>/dev/null | awk '{print $2}')

echo "`date +'%F %T'` The logbin_index is [$LOGBIN_INDEX]"

LOGBIN_BASENAME=`head -n 1 $LOGBIN_INDEX`

echo "`date +'%F %T'` The first binlog is [$LOGBIN_BASENAME]"

if [ ! -z "$LOGBIN_BASENAME" ]
then
   LOGBIN_NAME=`basename $LOGBIN_BASENAME | awk -F '.' '{print $1}'`
   echo "`date +'%F %T'` The binlog name is [$LOGBIN_NAME]"
else
   echo "`date +'%F %T'` Binary log is not enabled! exit!"
   exit 0
fi

if [ `ls -1 $BACKUP_DIR | grep $LOGBIN_NAME | wc -l` -eq 0 ]
then
   LOGBIN_LAST=`basename $LOGBIN_BASENAME`
else
   LOGBIN_LAST=`ls -1 $BACKUP_DIR | grep $LOGBIN_NAME | tail -n 1`
fi

echo "`date +'%F %T'` Starting live binlog backup from the latest file [$LOGBIN_LAST]"
mysqlbinlog $MYSQL_OPTIONS $LOGBIN_LAST --raw --read-from-remote-server --stop-never --result-file=$BACKUP_DIR 2>/dev/null
 
echo "`date +'%F %T'` mysqlbinlog exited with $? trying to reconnect in $SLEEP_RECONN seconds."
echo ""
sleep $SLEEP_RECONN
done


脚本参考:Backing up binary log files with mysqlbinlog

 

 

你可能感兴趣的:(MYSQL,MYSQL,备份还原,MYSQL,Log相关)