1、定时任务的逻辑
每日凌晨1点进行数据库备份;
每日凌晨0点删除超过30天的备份。
package com.XXXX.schedule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.IOException;
import java.sql.Date;
import java.time.LocalDate;
import java.util.Calendar;
import java.util.Map;
@Component
@EnableScheduling
@Slf4j
public class ScheduleHandle {
@Autowired
private JdbcUtils jdbcUtils;
@Value("${sqlFile.file}")
private String resourcePath;
/**
* 定时备份数据库信息
* 每日凌晨1点进行数据库备份
*/
@Scheduled(cron = "0 0 1 * * ?")
public void backUpDataBase() throws IOException {
log.info("======执行定时器:定时备份数据库=======");
String backUpPath = resourcePath+"/sql/" + Date.valueOf(LocalDate.now());
File backUpFile = new File(backUpPath);
if (!backUpFile.exists()) {
backUpFile.mkdirs();//创建日期文件夹
}
File dataFile = new File(backUpPath+"/campusportal"+System.currentTimeMillis()+".sql");
if (dataFile.exists()) {
System.out.println("文件名已存在,请更换");
return;
}
//拼接cmd命令
StringBuffer sb = new StringBuffer();
Map<String, String> dbInfo = jdbcUtils.getDBInfo();
sb.append("mysqldump");
sb.append(" -h"+dbInfo.get("host"));
sb.append(" -P"+dbInfo.get("port"));
sb.append(" -u"+dbInfo.get("userName"));
sb.append(" -p"+dbInfo.get("passWord"));
sb.append(" "+ dbInfo.get("dbName") +" > ");
sb.append(dataFile);
log.info("======数据库备份cmd命令为:"+sb.toString()+"=======");
try {
String[] cmd = { "/bin/sh", "-c", sb.toString()};//Linux系统
// String[] cmd = { "cmd", "/c", sb.toString()};//windows系统
Process exec = Runtime.getRuntime().exec(cmd);
if (exec.waitFor() == 0){
log.info("======数据库备份成功,路径为:"+dataFile+"=======");
} else {
System.out.println("======备份数据操作失败,返回值:"+exec.waitFor()+"=======");
}
} catch (Exception e) {
log.info("======数据库备份失败,异常为:"+e.getMessage()+"=======");
}
}
/**
* 定时删除数据库备份文件,只保留最近一个月
* 每日凌晨0点对距离现在30天
*/
@Scheduled(cron = "0 0 0 * * ?")
public void deleteBackUpDataBase() {
log.info("======执行定时器:定时删除备份数据库文件=======");
String backUpPath = resourcePath+"/sql";
File backUpFile = new File(backUpPath);
if (backUpFile.exists()) {
File[] files = backUpFile.listFiles();
for (File file : files) {
if (file.isDirectory()) {
Date date1 = Date.valueOf(file.getName());
Date date2 = Date.valueOf(LocalDate.now());
long betweenDay = dateCompte(date1, date2);
if (betweenDay > 30) {
File[] subFiles = file.listFiles();
for (File subFile : subFiles) {
subFile.delete();
}
file.delete();
log.info("======删除备份数据库文件成功=======");
}
}
}
}
}
public Long dateCompte(Date opDate,Date enDate){
Calendar calendar = Calendar.getInstance();
calendar.setTime(opDate);
long timeInMillis1 = calendar.getTimeInMillis();
calendar.setTime(enDate);
long timeInMillis2 = calendar.getTimeInMillis();
Long betweenDays = ((timeInMillis2 - timeInMillis1) / (1000L * 3600L * 24L));
return betweenDays;
}
}
2、jdbcUtils
package com.XXXX.schedule;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.HashMap;
@Component
public class JdbcUtils {
@Value("${spring.datasource.druid.master.url}")
private String url;
@Value("${spring.datasource.druid.master.username}")
private String username;
@Value("${spring.datasource.druid.master.password}")
private String password;
public HashMap<String, String> getDBInfo() {
String[] split = url.split(":");
// String host = String.format("%s:%s:%s", split[0], split[1], split[2]);
String host = split[2].substring(2);
String[] portSplit = split[3].split("/");
String port = portSplit[0];
String[] databaseSplit = portSplit[1].split("\\?");
String dbName = databaseSplit[0];//数据库名
HashMap<String, String> result = new HashMap<>();
result.put("url",url);
result.put("host",host);
result.put("port",port);
result.put("dbName",dbName);
result.put("userName",username);
result.put("passWord",password);
return result;
}
}