为什么写这篇文章
最近项目里面需要定时备份mysql的数据,网上找了下,找到了一些比较好的解决方案。但是发现有几个地方与自己不匹配,我期望有如下
- 备份过程不能锁表,网上很多都是会锁表
- 备份定时任务无法执行,但是手动执行又可以
- 由于我的数据库存在很多log日志,这部分无需备份,所以忽略了部分表
- 最好有定时任务的执行日志,我好判断是否成功执行
基于上,我做了一些修改,特此记录,以便查阅。
正文
一、新建文件夹
mkdir -p /home/mysqlbak/log
mkdir /mysqlbackdata
二、在/home/mysqlbak新建备份脚本mysql_bak.sh
vi /home/mysqlbak/mysql_bak.sh
#!/bin/bashmysql_user="yrt" #MySQL备份用户
mysql_password="qF-JOJOIq_>4" #MySQL备份用户的密码
mysql_host="192.168.3.193"
mysql_port="3306"
mysql_charset="utf8" #MySQL编码
backup_db_arr=("xx" "xx") #要备份的数据库名称,多个用空格分开隔开 如("db1" "db2" "db3")
backup_location=/mysqlbackdata #备份数据存放位置,末尾请不要带"/",此项可以保持默认,程序会自动创建文件夹
expire_backup_delete="ON" #是否开启过期备份删除 ON为开启 OFF为关闭
expire_days=30 #过期时间天数 默认为三天,此项只有在expire_backup_delete开启时有效
backup_time=`date +%Y%m%d%H%M` #定义备份详细时间
backup_Ymd=`date +%Y-%m-%d` #定义备份目录中的年月日时间
backup_3ago=`date -d '3 days ago' +%Y-%m-%d` #3天之前的日期
backup_dir=$backup_location/$backup_Ymd #备份文件夹全路径
welcome_msg="Welcome to use MySQL backup tools!" #欢迎语
mysql_ps=`ps -ef |grep mysql |wc -l`
mysql_listen=`netstat -an |grep LISTEN |grep $mysql_port|wc -l`
if [ [$mysql_ps == 0] -o [$mysql_listen == 0] ]; thenecho "ERROR:MySQL is not running! backup stop!"exit
elseecho $welcome_msg
fi
mysql -h$mysql_host -P$mysql_port -u$mysql_user -p$mysql_password <<end
use yrt;
exit
end
flag=`echo $?`
if [ $flag != "0" ]; thenecho "ERROR:Can't connect mysql server! backup stop!"exit
elseecho "MySQL connect ok! Please wait......"# 判断有没有定义备份的数据库,如果定义则开始备份,否则退出备份if [ "$backup_db_arr" != "" ];then#dbnames=$(cut -d ',' -f1-5 $backup_database)#echo "arr is (${backup_db_arr[@]})"for dbname in ${backup_db_arr[@]}doecho "database $dbname backup start..."`mkdir -p $backup_dir``mysqldump -h$mysql_host -P$mysql_port -u$mysql_user -p$mysql_password $dbname --single-transaction --skip-lock-tables --ignore-table=yrt.sys_oper_post_log --ignore-table=yrt.sys_oper_log --default-character-set=$mysql_charset | gzip > $backup_dir/$dbname-$backup_time.sql.gz`flag=`echo $?`if [ $flag == "0" ];thenecho "database $dbname success backup to $backup_dir/$dbname-$backup_time.sql.gz"elseecho "database $dbname backup fail!"fidoneelseecho "ERROR:No database to backup! backup stop"exitfi# 如果开启了删除过期备份,则进行删除操作if [ "$expire_backup_delete" == "ON" -a "$backup_location" != "" ];then#`find $backup_location/ -type d -o -type f -ctime +$expire_days -exec rm -rf {} \;``find $backup_location/ -type d -mtime +$expire_days | xargs rm -rf`echo "Expired backup data delete complete!"fiecho "All database backup success! Thank you!"exit
fi
echo $(date)
修改mysql_bak.sh脚本属性,赋予执行权限
chmod 777 /home/mysqlbak/mysql_bak.sh
chmod +x /home/mysqlbak/mysql_bak.sh
可以执行下这个脚本测试下能否生成备份文件
sh /home/mysqlbak/mysql_bak.sh
输出如下说明成功了
定时执行备份脚本
crontab -e
加入如下内容,我的定时任务每天的1点和13点执行
0 1,13 * * * /home/mysqlbak/mysql_bak.sh >> /home/mysqlbak/logs/bak_log.log
启动定时任务并设置开机自动启动
/bin/systemctl start crond.service
systemctl enable crond.service
参考
https://blog.csdn.net/qq_37798548/article/details/83306718/