自动备份数据库
情景描述
因为有很长时间没有备份数据库的数据,致使服务器瘫痪之后只能恢复到一个月前的数据,造成很多BookMark使用者的不便,所以决定写一个脚本来实现如下的功能:
- 定期备份数据库(测试阶段先定为1小时)
- 每次备份之后,将备份结果以邮件的方式通知管理员
- 将备份的数据传到七牛云上
代码实现
发送邮件的代码实现
#!/bin/bash # sendmail.sh echo `echo $1` | mail -s "the information of dumping datebase.sql from igouc.com" -t XXXXX@XXXX.com -a From:XXXX@igouc.com
定期备份数据库代码实现
#!/bin/bash # dumpdatabases.sh echo "start dumpdatabases ......" datetime=`date +%s` while true do nowdatetime=`date +%s` diffnum=$((nowdatetime - datetime)) echo "nowdatetime=$nowdatetime; datetime=$datetime; diffnum=$diffnum " regunum=$((60*60)) if [ $diffnum -ge $regunum ] then echo "-------------- dump databases start -----------------" #打印日志 echo "----------- `date` -------------" | tee -a log.txt rm bookmark* rm myblog* bm_filename="bookmark_database_`date +%y%m%d%H%M%S`.sql" wb_filename="myblog_database_`date +%y%m%d%H%M%S`.sql" counter=0 if `/usr/bin/mysqldump -uroot -pxxxxxx(your mysql's password) bm > $bm_filename` then ((counter++)) #打印日志 echo "$bm_filename Dump Successed" | tee -a log.txt else #打印日志 echo "$bm_filename Dump Failed" | tee -a log.txt fi if `/usr/bin/mysqldump -uroot -pgc wb > $wb_filename` then counter=$(($counter+6)) #打印日志 echo "$wb_filename Dump Successed" | tee -a log.txt else #打印日志 echo "$wb_filename Dump Failed" | tee -a log.txt fi echo "-------------- dump databases end -----------------" datetime=$nowdatetime case $counter in 0) ./sendmail.sh "Sorry: Full Backup Filed" ;; 6) ./sendmail.sh "Sorry: bookmark backup filed, myblog backup success: $wb_filename" ;; 1) ./sendmail.sh "Sorry: myblog backup filed, bookmark backup success: $bm_filename" ;; 7) ./sendmail.sh "Congratulations: All Backup Success, $wb_filename ; $bm_filename" ;; *) ./sendmail.sh "ERROR: Programming Error" ;; esac fi sleep 60 done echo "dumpdatabases stop......"
将数据库备份文件上传至七牛云
七牛给出了很清晰明了的文档,这里请大家自行查阅文档。我这里只给出了在Main函数里新启动线程并且定时上传的代码(定时时间为1小时)
public static void main(String[] args) { new Thread(){ @Override public void run() { while(true){ try { System.out.println("开始上传....."); UploadDumpFile uploadDumpFile = new UploadDumpFile(); uploadDumpFile.upload(); System.out.println("上传完成......"); this.sleep(1000*60*60); } catch (Exception e) { System.out.println("上传失败!"); e.printStackTrace(); break; } } } }.start(); }
这样,数据库文件就会每隔一小时备份一次并且上传到云端。
如果您是python的使用者,那么相信这种操作对您来说肯定是so easy
效果
手机收到邮件截图
上传到七牛的截图
转发请注明出处,谢谢合作GC博客