考虑到数据库安全的时候,当时想到是否可以定时备份上传到七牛云,这样系统被搞了,也不怕,经济又实惠,百度一下果然有。
#!/bin/bash
# 设定 文件夹
date_now=`date +%Y_%m_%d`
password=你的密码
user=数据库用户
backFileName=/mnt/cmswing_$date_now.sql
#备份数据库
mysqldump -u$user -p$password cmswing > $backFileName
let exec = require('child_process').exec
async shell(cmdStr) {
return new Promise((resolve, reject) => {
exec(cmdStr, async (err, stdout, stderr) => {
if (err) return reject(false);
return resolve(true)
})
})
}
3.上传七牛云
/**
* 备份到七牛云
*/
async backuptoqiniuAction() {
let cmdStr = 'sh /mnt/***/***/backup.sh';
let now = new Date().getTime(), last = now - 24 * 3600 * 1000;
let time = this.moment(now).format('YYYY_MM_DD');
let lasttime = this.moment(last).format('YYYY_MM_DD');
let filepath = path.resolve(think.ROOT_PATH, `../../cmswing_${time}.sql`);
let lastfilepath = path.resolve(think.ROOT_PATH, `../../cmswing_${lasttime}.sql`);
//防止手动多次备份
if (think.isFile(filepath)) {
if (!this.isCli) return this.fail('已备份');
return;
}
//移除昨天的
if (think.isFile(lastfilepath)) fs.unlink(lastfilepath, () => { });
let result = await this.shell(cmdStr);
if (result && think.isFile(filepath)) {
let qiniu = think.extService('qiniu', 'attachment');
let res = await qiniu.uploadpic(filepath, `cmswing_${time}.sql`);
if (res) await qiniu.remove(`cmswing_${lasttime}.sql`);//移除七牛
if (res && !this.isCli) {
return this.success({ 'name': '备份七牛云成功' });
}
}
if (!this.isCli) {
return this.fail('备份七牛云失败');
}
}
4.定时任务
我用的是thinkjs框架,因此在配置文件下写定时任务
{
cron: '0 0 1 * *',// 每天的凌晨1点触发
handle: 'admin/database/backuptoqiniu',
type: 'one',
enable: true// 关闭当前定时器,默认true
},