关于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!

The steps to create and manage user accounts in MySQL are as follows: 1. Create a user: Use CREATEUSER'newuser'@'localhost'IDENTIFIEDBY'password'; 2. Assign permissions: Use GRANTSELECT, INSERT, UPDATEONmydatabase.TO'newuser'@'localhost'; 3. Fix permission error: Use REVOKEALLPRIVILEGESONmydatabase.FROM'newuser'@'localhost'; then reassign permissions; 4. Optimization permissions: Use SHOWGRA

MySQL is suitable for rapid development and small and medium-sized applications, while Oracle is suitable for large enterprises and high availability needs. 1) MySQL is open source and easy to use, suitable for web applications and small and medium-sized enterprises. 2) Oracle is powerful and suitable for large enterprises and government agencies. 3) MySQL supports a variety of storage engines, and Oracle provides rich enterprise-level functions.

The disadvantages of MySQL compared to other relational databases include: 1. Performance issues: You may encounter bottlenecks when processing large-scale data, and PostgreSQL performs better in complex queries and big data processing. 2. Scalability: The horizontal scaling ability is not as good as Google Spanner and Amazon Aurora. 3. Functional limitations: Not as good as PostgreSQL and Oracle in advanced functions, some functions require more custom code and maintenance.

MySQL supports four JOIN types: INNERJOIN, LEFTJOIN, RIGHTJOIN and FULLOUTERJOIN. 1.INNERJOIN is used to match rows in two tables and return results that meet the criteria. 2.LEFTJOIN returns all rows in the left table, even if the right table does not match. 3. RIGHTJOIN is opposite to LEFTJOIN and returns all rows in the right table. 4.FULLOUTERJOIN returns all rows in the two tables that meet or do not meet the conditions.

MySQL's performance under high load has its advantages and disadvantages compared with other RDBMSs. 1) MySQL performs well under high loads through the InnoDB engine and optimization strategies such as indexing, query cache and partition tables. 2) PostgreSQL provides efficient concurrent read and write through the MVCC mechanism, while Oracle and Microsoft SQLServer improve performance through their respective optimization strategies. With reasonable configuration and optimization, MySQL can perform well in high load environments.

InnoDBBufferPool reduces disk I/O by caching data and indexing pages, improving database performance. Its working principle includes: 1. Data reading: Read data from BufferPool; 2. Data writing: After modifying the data, write to BufferPool and refresh it to disk regularly; 3. Cache management: Use the LRU algorithm to manage cache pages; 4. Reading mechanism: Load adjacent data pages in advance. By sizing the BufferPool and using multiple instances, database performance can be optimized.

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

MySQL is worth learning because it is a powerful open source database management system suitable for data storage, management and analysis. 1) MySQL is a relational database that uses SQL to operate data and is suitable for structured data management. 2) The SQL language is the key to interacting with MySQL and supports CRUD operations. 3) The working principle of MySQL includes client/server architecture, storage engine and query optimizer. 4) Basic usage includes creating databases and tables, and advanced usage involves joining tables using JOIN. 5) Common errors include syntax errors and permission issues, and debugging skills include checking syntax and using EXPLAIN commands. 6) Performance optimization involves the use of indexes, optimization of SQL statements and regular maintenance of databases.


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

WebStorm Mac version
Useful JavaScript development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

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