MySQL binlog-server搭建
MySQL binlog-server搭建
binlog在备份中起着至关重要的作用,备份binlog文件时,只能先在本地备份,然后才能传送到远程服务器上。从MySQL5.6版本后,可以利用mysqlbinlog命令把远程机器的日志备份到本地目录,这样就更加方便地实现binlog日志的安全备份。
常用的参数
-R | –read-from-remote-server
表示开启binlog备份,在对应的主节点上请求binlog到本地。–raw
被复制过来的binlog以二进制的格式存放,如果不加该参数则为text格式。-r | –result-file
指定目录或文件名:
若指定了–raw参数,-r的值指定binlog的存放目录和文件名前缀;若没有指定–raw参数,-r的值指定文本存放的目录和文件名。-t
这个选项代表从指定的binlog开始拉取,直到当前主节点上binlog的最后一个。–stop-never
持续连续从主节点拉取binlog,持续备份到当前最后一个,并继续下去。该参数包含-t–stop-never-slave-server-id
默认值65535,用于在多个mysqlbinlog进程或者从服务器的情况下,避免ID冲突。
# ERROR: Got error reading packet from server: A slave with the same server_uuid/server_id as this slave has connected to the master;
the first event 'my3306_binlog.000045' at 4, the last event read from
'/data/mysql/mysql3306/logs/my3306_binlog.000062' at 194.
备份示例
mysqlbinlog -h192.168.56.100 -uwanbin -pmysql \
-R --raw --stop-never my3306_binlog.000045 --stop-never-slave-server-id=20003306 \
-r /data/backup/binlog_bk/ &
备份binlog shell脚本
#!/bin/sh
BACKUP_BIN=/usr/local/mysql/bin/mysqlbinlog
LOCAL_BACKUP_DIR=/data/backup/binlog_bk
BACKUP_LOG=/data/backup/bakbinlog.log
REMOTE_HOST=192.168.56.100
#REMOTE_PORT=3306
SERVER_ID=20003306
REMOTE_USER=wanbin
REMOTE_PASS=mysql
#time to wait before reconnecting after failure
SLEEP_SECONDS=10
##create local_backup_dir if necessary
##mkdir -p ${LOCAL_BACKUP_DIR}
cd ${LOCAL_BACKUP_DIR}
## 运行while循环,连接断开后等待指定时间,重新连接
while :
FIRST_BINLOG=$(mysql --host=${REMOTE_HOST} --user=${REMOTE_USER} --password=${REMOTE_PASS} -e 'show binary logs'|grep -v "Log_name"|awk '{print $1}'|head -n 1)
do
if [ `ls -A "${LOCAL_BACKUP_DIR}" |wc -l` -eq 0 ];then
LAST_FILE=${FIRST_BINLOG} ##如果备份目录中没有备份文件则 LAST_FILE=FIRST_FILE
else
LAST_FILE=`ls -l ${LOCAL_BACKUP_DIR} |tail -n 1 |awk '{print $9}'` ##last_file取序列最大的binlog文件
fi
${BACKUP_BIN} -R --raw --host=${REMOTE_HOST} --user=${REMOTE_USER} --password=${REMOTE_PASS} ${LAST_FILE} --stop-never --stop-never-slave-server-id=${SERVER_ID}
echo "`date +"%Y/%m/%d %H:%M:%S"` mysqlbinlog停止,返回代码:$?" | tee -a ${BACKUP_LOG}
echo "${SLEEP_SECONDS}秒后再次连接并继续备份" | tee -a ${BACKUP_LOG}
sleep ${SLEEP_SECONDS}
done