MySQL的binlog日志是实现实时备份的关键,但是本地备份不能解决灾备问题,将binlog远程实时备份以实现灾备机制,防止硬盘损坏、删库等风险
参考:https://blog.csdn.net/a12345678n/article/details/105066462 (opens new window)
原理:使用mysqlbinlog工具在备份服务器上拉取binlog文件
mysqlbinlog参数:
- --read-from-remote-server 从远程服务器读取
- --stop-never 一直读取
# 示例
需指定一个binlog名称,会从指定的名称开始往后同步到最后一个binlog文件 当服务器刷新binlog时会自动同步最新的binlog文件
mysqlbinlog --raw --read-from-remote-server --stop-never --host=192.168.1.216 --port=3306 --user=grass --password=grass mysql-bin.000001
# 同步binlog日志脚本:
- 从已同步的最新的binlog文件名称开始同步,不存在就从第一个开始同步
- 当MySQL服务器暂时不可能时,停止同步,恢复时继续同步
vim /usr/local/scripts/mysqlbinlog-sync.sh
#!/bin/sh
BACKUP_BIN="/usr/bin/mysqlbinlog"
BACKUP_DIR="/data/mysql/binlog/"
LOGFILE="/var/log/mysqlbinlog-sync.log"
REMOTE_HOST="192.168.1.216"
REMOTE_PORT="3306"
REMOTE_USER="grass"
REMOTE_PASS="grass"
SLEEP_SECONDS=60
MYSQLCOMMAND="mysql -h$REMOTE_HOST -u$REMOTE_USER -p$REMOTE_PASS -P$REMOTE_PORT --protocol=tcp -N -e "
FIRST_BINLOG=$($MYSQLCOMMAND "show binary logs" 2>/dev/null|head -1|awk '{print $1}')
if [ ! $FIRST_BINLOG ]
then
echo "无法获取binlog信息,请检查数据库帐号权限和当前数据库是否打开binlog日志"
exit 1
fi
save_log() {
echo $1;
echo "[`date +'%Y-%m-%d %H:%M:%S'`] $1" >> $LOGFILE
}
mkdir -p $BACKUP_DIR
cd $BACKUP_DIR
while :
do
if [ `ls -A "${BACKUP_DIR}" |wc -l` -eq 0 ];then
LAST_FILE=${FIRST_BINLOG}
else
LAST_FILE=`ls -t ${BACKUP_DIR} | head -n 1`
fi
save_log "start backup mysqlbinlog:$LAST_FILE"
$BACKUP_BIN --raw --read-from-remote-server --stop-never --host=${REMOTE_HOST} --port=${REMOTE_PORT} --user=${REMOTE_USER} --password=${REMOTE_PASS} ${LAST_FILE} 2>/dev/null
save_log "mysqlbinlog stop:$?"
sleep $SLEEP_SECONDS
done
设置脚本自动在后台运行,并设置开机启动
cat > /usr/lib/systemd/system/mysqlbinlog-sync.service << EOF
[Unit]
Description=mysqlbinlog-sync
After=network.target
[Service]
User=root
Group=root
ExecStart=/bin/bash /usr/local/scripts/mysqlbinlog-sync.sh
ExecStop=
Restart=on-failure
[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
systemctl start mysqlbinlog-sync
systemctl enable mysqlbinlog-sync
🕑 最后更新时间: 2022-10-15 13:42