How to backup script for binlog in MySQL
关于MySQL的二进制日志(binlog),我们都知道二进制日志(binlog)非常重要,尤其当你需要point to point灾难恢复的时侯,所以我们要对其进行备份。关于二进制日志(binlog)的备份,可以基于flush logs方式先切换binlog,然后拷贝&压缩到到远程服务器或本地服务器的其他存储上,例如挂载的NAS存储,也可以使用mysqlbinlog实现binlog的备份,可以实现MySQL二进制日志(binlog)的本地备份或远程备份。最终将MySQL二进制日志(binlog)备份文件存储到磁带上。各个公司的备份策略或备份工具有所不同,这里不做展开,我们主要考虑MySQL二进制日志(binlog)备份方案/策略尽可能尽善尽美,在一些极端情况下少丢失数据。例如,第一种方式,这种备份方式都是周期性的,如果在某个周期中,遇到一些极端情况,例如服务器宕机了,硬盘损坏了,就可能导致这段时间的binlog丢失了。而且这个周期时间太长,二进制日志(binlog)丢失的风险就越大,如果这个周期太短,频繁切换binlog也不好。所以还是使用mysqlbinlog来备份二进制日志(binlog),这里主要介绍一下我写的MySQL二进制日志的备份脚本,这个脚本参考了如何远程备份MySQL binlog[1]中的脚本,但是在其基础上做了很多改进和完善:
参考资料中的脚本由于使用了循环操作,不适合在作业中调用。一般需要手工执行脚本,让其在后台运行。遇到服务器重启或其他异常情况,此脚本可能出现未能执行的情况。
增加了mysql_binlog_backup_job.sh脚本,作业会定期调用此脚本,此脚本会判断mysqlbinlog是否还在执行二进制日志备份。即使遇到了数据库服务器重启等情况,备份MySQL的二进制日志(binlog)也不会成为问题。
不用手工指定第一个binlog文件参数,采用从数据库读取binlog的值.如果是在本地服务器执行binlog的备份,还可以从二进制日志索引文件中获取(参考脚本注释部分)
使用mysql_config_editor配置账号密码,避免在脚本中使用数据库用户的明文密码。
邮件告警处理。
在使用脚本前,必须配置mailx,创建数据库连接账号
create user bkuser@'xxx.xxx.xxx.xxx' identified by "******"; grant replication client on *.* to bkuser@'%'; grant replication slave on *.* to bkuser@'%';
这个根据实际情况调整,例如我就是使用Xtrabackup的账号来备份MySQL的binlog。 另外,如果在MySQL数据库服务器本机备份binlog,那么就在本机安全加密登录,如果是在远程服务器备份binlog的话,就在远程服务器配置
$ mysql_config_editor set --login-path=server1_dbbackup -h xxx.xxx.xxx.xxx -ubkuser -p -P 3306 Enter password:
mysql_binlog_backup_job.sh脚本
#!/bin/sh ######################################################################################### # # # This script is used for mysql binlog backup. # # # # ####################################################################################### # # # ScriptName : mysql_binlog_backup_job.sh # # Author : 潇湘隐者 # # CerateDate : 2017-04-14 # # Description : # #---------------------------------------------------------------------------------------# # 作业中调用此脚本,然后此脚本去调用mysql_binlog_backup.sh执行 # # MySQL的二进制日志备份(将MySQL的二进制日志备份到NAS存储或备份存# # 储上),此脚本还会判断mysqlbinlog是否在一直在备份二进制日志, # # 如果是的话,则退出当前脚本。如果mysqlbinlog已经由于服务器重 # # 启等原因退出了,则会重新调用mysql_binlog_backup.sh # #***************************************************************************************# # Version Modified Date Description # #***************************************************************************************# # V.1.0 2016-06-20 create the script for mysql binlog backp # # V.1.1 2016-07-26 fix some bug # # V.1.2 2023-04-14 $FIRST_BINLOG从MySQL中获取,即使远程备份也不用手工 # # 设定,本地备份也可以这种方式,本地备份默认从 # # mysql binlog index file读取 # ######################################################################################### #mysql binlog备份文件的保留天数 KEEPY_DAYS=7 FIRST_BINLOG='' LOG_DATE=$(date +%Y_%m_%d_%H_%M_%S) BACKUP_DATE=$(date +%Y_%m_%d_%H_%M_%S) LOCAL_BACKUP_DIR=/dbbackup/mysql_backup/db_backup/binlog_backup #MYSQL_BINLOG_INDEX=/data/bin_logs/mysql_binlog.index MYSQL_CMD=/opt/mysql/mysql8.0/bin/mysql BACKUP_LOG_PATH=/dbbackup/mysql_backup/logs ERROR_LOG=${BACKUP_LOG_PATH}/binlog_backup_error_${BACKUP_DATE}.log FILE_TYPE="mysql_binlog.*" SQL_TEXT='show binary logs' MAIL_TO="xxxx@xxx.com.cn" MAIL_FROM="xxxx@xxx.com.cn" MYSQL_LOGIN_PATH=server1_dbbackup error() { echo "$1" 1>&2 echo "$1" >> ${ERROR_LOG} echo "$1" | mailx -s "The binlog backup on the server `hostname` failed ,please check the log!" -r ${MAIL_FROM} ${MAIL_TO} exit 1 } ##目录不存在则创建目录 if [ ! -d $BACKUP_LOG_PATH ];then mkdir -p $BACKUP_LOG_PATH fi if [ ! -x /bin/mailx ];then error "{LOG_DATE}:mailx did not exists!" fi if [ ! -x $MYSQL_CMD ];then error "{LOG_DATE}: mysql client did not exists!" fi #SQL_RESULT=`mysql -h${REMOTE_HOST} -P${PORT} -u${USER_NAME} -p${PASSWORD} ${DATABASE_NAME} -Bse "${SQL_TEXT}"` SQL_RESULT=`$MYSQL_CMD --login-path=${MYSQL_LOGIN_PATH} -Bse "${SQL_TEXT}"` FIRST_BINLOG=`echo ${SQL_RESULT} | awk '{print $1}'` echo $FIRST_BINLOG if [ ! $FIRST_BINLOG ];then error "${LOG_DATE}: please check the mysql binlog" fi ##create local_backup_dir if this folder is not exists if [ ! -d ${LOCAL_BACKUP_DIR} ];then mkdir -p ${LOCAL_BACKUP_DIR} fi if [ ! -e ${MYSQL_BINLOG_INDEX} ];then error "${LOG_DATE}:mysql binlog index file did not exists, please check it!" fi #删除KEEPY_DAYS天之前的binlog备份文件 find ${LOCAL_BACKUP_DIR} -name "${FILE_TYPE}" -type f -mtime +$KEEPY_DAYS -delete #删除30天前的错误日志 find ${BACKUP_LOG_PATH} -name "binlog_backup_error*.log" -mtime 30 -delete process_num=$(ps -ef | grep -w mysqlbinlog | grep -v grep |wc -l) if [ ${process_num} -ge 1 ];then exit 1 else #如果是在本机备份binlog到NAS存储或备份存储上,从二进制文件的索引获取当前MySQL数据库最小的binlog文件 #如果是远程备份二进制日志(binlog)的话,则使用下面注释的脚本获取 #FIRST_BINLOG=$(head -1 ${MYSQL_BINLOG_INDEX}) #FIRST_BINLOG=$(find ${LOCAL_BACKUP_DIR} -name "mysql_binlog.*" -printf "%p\t%C@\n" | sort -k2 -g |head -1 | awk '{print $1}' | awk -F "/" '{print $NF}') echo ${FIRST_BINLOG} nohup sh /dbbackup/mysql_backup/scripts/mysql_binlog_backup.sh ${FIRST_BINLOG} ${LOCAL_BACKUP_DIR} ${FILE_TYPE} & fi
mysql_binlog_backup.sh脚本
#!/bin/sh ######################################################################################### # # # This script is used for mysql binlog local or remote backup. # # # # ####################################################################################### # # # ScriptName : mysql_binlog_backup.sh # # Author : Kerry # # CerateDate : 2017-04-14 # # Description : # #---------------------------------------------------------------------------------------# # 此脚本参考了https://www.cnblogs.com/ivictor/p/5502240.html # # 的脚本,在它的基础上做了一些改进,例如,ivitcor中脚本备份binlog# # 如果服务器重启了,则必须手动执行脚本....... # #***************************************************************************************# # Version Modified Date Description # #***************************************************************************************# # V.1.0 2016-06-20 create the script for mysql binlog backp # # V.1.1 2016-07-26 fix some bug # ######################################################################################### BACKUP_BIN=/opt/mysql/mysql8.0/bin/mysqlbinlog BACKUP_LOG_PATH=/dbbackup/mysql_backup/logs LOG_DATE=$(date +%Y_%m_%d_%H_%M_%S) BACKUP_LOG=${BACKUP_LOG_PATH}/binlog_backup.log ERROR_LOG=${BACKUP_LOG_PATH}/binlog_backup_error_${LOG_DATE}.log #复制二进制日志的主机,可以远程MySQL数据库也可以是本机 MYSQL_LOGIN_PATH=server1_dbbackup #time to wait before reconnecting after failure SLEEP_SECONDS=10 MAIL_TO="xxx@xxx.com.cn" MAIL_FROM="xxx@xxx.com.cn" error() { echo "$1" 1>&2 echo "$1" >> ${ERROR_LOG} echo "$1" | mailx -s "The binlog backup on the server `hostname` failed ,please check the log!" -r ${MAIL_FROM} ${MAIL_TO} exit 1 } ##目录不存在则创建目录 if [ ! -d $BACKUP_LOG_PATH ];then mkdir -p $BACKUP_LOG_PATH fi if [ "$#" -ne 3];then error "${LOG_DATE}:you must input 3 arguments" fi if [ ! $1 ];then error "${LOG_DATE}:first_binlog arguments is null" else FIRST_BINLOG=$1 fi if [ ! $2 ];then error "${LOG_DATE}:local_backup_dir arguments is null" else LOCAL_BACKUP_DIR=$2 fi if [ ! $3 ];then error "${LOG_DATE}:file_type arguments is null" else FILE_TYPE=$3 fi ##检查mysqlbinlog二进制文件是否存在 if [ ! -x ${BACKUP_BIN} ];then error "${LOG_DATE}:mysqlbinlog did not exists, please check it!" fi cd ${LOCAL_BACKUP_DIR} ## 运行while循环,连接断开后等待指定时间,重新连接 while : do #如果当前备份二进制日志目录为空,则使用MySQL实例最小的二进制日志文件名 if [ `ls -A "${LOCAL_BACKUP_DIR}" |wc -l` -eq 0 ];then LAST_BINLOG_FILE=${FIRST_BINLOG} else #LAST_FILE=`ls -l ${LOCAL_BACKUP_DIR} | grep -v backuplog |tail -n 1 |awk '{print $9}'` #echo ${LOCAL_BACKUP_DIR} #echo ${FILE_TYPE} #取mysqlbinlog备份的最后一个binlog文件名 LAST_BINLOG_FILE=`find ${LOCAL_BACKUP_DIR} -name "${FILE_TYPE}" -printf "%p\t%C@\n" | sort -k2 -g |tail -1 | awk '{print $1}' | awk -F "/" '{print $NF}'` fi #${BACKUP_BIN} --login-path=${MYSQL_LOGIN_PATH} --read-from-remote-server --raw --stop-never --host=${REMOTE_HOST} --port=${REMOTE_PORT} ${LAST_BINLOG_FILE} ${BACKUP_BIN} --login-path=${MYSQL_LOGIN_PATH} --read-from-remote-server --raw --stop-never ${LAST_BINLOG_FILE} echo "`date +"%Y/%m/%d %H:%M:%S"` mysqlbinlog停止,返回代码:$?" | tee -a ${BACKUP_LOG} echo "${SLEEP_SECONDS}秒后再次连接并继续备份" | tee -a ${BACKUP_LOG} sleep ${SLEEP_SECONDS} done
配置作业
*/10 * * * * /dbbackup/mysql_backup/scripts/mysql_binlog_backup_job.sh >> /dbbackup/mysql_backup/logs/mysql_binlog_back.log 2>&1
The above is the detailed content of How to backup script for binlog in MySQL. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

You can open phpMyAdmin through the following steps: 1. Log in to the website control panel; 2. Find and click the phpMyAdmin icon; 3. Enter MySQL credentials; 4. Click "Login".

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

Redis uses a single threaded architecture to provide high performance, simplicity, and consistency. It utilizes I/O multiplexing, event loops, non-blocking I/O, and shared memory to improve concurrency, but with limitations of concurrency limitations, single point of failure, and unsuitable for write-intensive workloads.

MySQL and SQL are essential skills for developers. 1.MySQL is an open source relational database management system, and SQL is the standard language used to manage and operate databases. 2.MySQL supports multiple storage engines through efficient data storage and retrieval functions, and SQL completes complex data operations through simple statements. 3. Examples of usage include basic queries and advanced queries, such as filtering and sorting by condition. 4. Common errors include syntax errors and performance issues, which can be optimized by checking SQL statements and using EXPLAIN commands. 5. Performance optimization techniques include using indexes, avoiding full table scanning, optimizing JOIN operations and improving code readability.

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

Effective monitoring of Redis databases is critical to maintaining optimal performance, identifying potential bottlenecks, and ensuring overall system reliability. Redis Exporter Service is a powerful utility designed to monitor Redis databases using Prometheus. This tutorial will guide you through the complete setup and configuration of Redis Exporter Service, ensuring you seamlessly build monitoring solutions. By studying this tutorial, you will achieve fully operational monitoring settings
