后端代码定时备份数据库
@Value("${command}") private String command; @Value("${bakFilePath}") private String bakFilePath; @Value("${bakFileName}") private String bakFileName; @Value("${cleanCmdPath}") private String cleanCmdPath;
@Scheduled(cron ="${bakupDataBaseCron}")
public void backUpDateBase() {
logger.info("开始备份数据库....");
try {
File file = new File(bakFilePath);
if (!file.exists()) {
file.mkdir();
}
String dataStr = DateUtils.formatDate(new Date(), "yyyyMMddHHmm");
String name = bakFileName +"_"+ dataStr + ".sql";
File datafile = new File(bakFilePath , name);
if (!datafile.exists()) {
datafile.createNewFile();
}
logger.info("创建文件...datafile:"+datafile.getPath());
//拼接cmd命令
String commands = command +" "+ bakFilePath + File.separatorChar + name;
logger.info("备份命令为,commands:" + commands);
//带空格的命令 需要特殊传入,否则不能执行
Process exec = Runtime.getRuntime().exec(new String[]{"/bin/sh","-c",commands});
if (exec.waitFor() == 0) {
logger.info("数据库备份成功,备份路径为:" +datafile.getPath());
}
}catch (Exception e){
logger.error("数据库备份失败..", e);
}
}
public void cleanBakDateBase() { logger.info("开始清理备份数据库...."); try { logger.info("要执行的命令为,commands:" +cleanCmdPath); Process exec = Runtime.getRuntime().exec(cleanCmdPath); if (exec.waitFor() == 0) { logger.info("清除备份数据库命令执行成功..." ); } }catch (Exception e){ logger.error("清除备份数据库命令执行失败..", e); } }
#定时清理备份的数据库 bakupDataBaseCron: 0 */1 * * * ? bakFilePath : /home/jysp bakFileName : ycxs1000bak command : mysqldump -h 127.0.0.1 -P端口 -u 数据库用户名 -p数据库密码 数据库名 >
#定时清理备份的数据库
cleanBakDateBase: 0 0 1 * * ?
cleanCmdPath: /home/jysp/workspace/bin/cleanup.sh