package com.sportrecovery.common;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.sportrecovery.controller.BackupController;
import com.sportrecovery.entity.Backup;
import com.sportrecovery.entity.BackupConfig;
import com.sportrecovery.mapper.BackupConfigMapper;
import com.sportrecovery.mapper.BackupMapper;
import com.sportrecovery.util.HttpResult;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
@Configuration //1.主要用于标记配置类,兼备Component的效果。
@EnableScheduling // 2.开启定时任务
public class TimingController implements SchedulingConfigurer {
@Autowired
BackupConfigMapper backupConfigMapper;
@Autowired
BackupMapper backupMapper;
@Autowired
BackupController backupController;
@Mapper
public interface CronMapper {
@Select("select cron from backup_config limit 1")
public String getCron();
}
@Autowired //注入mapper
@SuppressWarnings("all")
CronMapper cronMapper;
/**
* 执行定时任务.
*/
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.addTriggerTask(
//1.添加任务内容(Runnable)
// () -> System.out.println("执行动态定时任务: " + LocalDateTime.now().toLocalTime()),
() -> click(),
//2.设置执行周期(Trigger)
triggerContext -> {
//2.1 从数据库获取执行周期
// BackupConfig backupConfig = backupConfigMapper.selectById(1);
// String cron = backupConfig.getCron();
String cron = cronMapper.getCron();
System.out.println(cron);
//2.2 合法性校验.
if (StringUtils.isEmpty(cron)) {
// Omitted Code ..
}
//2.3 返回执行周期(Date)
return new CronTrigger(cron).nextExecutionTime(triggerContext);
}
);
}
//手动备份
public void click() {
BackupConfig backupConfig = backupConfigMapper.selectById(1);
String savePath = backupConfig.getUrl();
String times = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
String url = savePath + "backup_" + times + ".sql";
File saveFile = new File(savePath);
if (!saveFile.exists()) {// 如果目录不存在
saveFile.mkdirs();// 创建文件夹
}
if (!savePath.endsWith(File.separator)) {
savePath = savePath + File.separator;
}
//拼接命令行的命令
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("mysqldump").append(" --opt").append(" -h").append("127.0.0.1");
stringBuilder.append(" --user=").append("root").append(" --password=").append("root")
.append(" --lock-all-tables=true");
stringBuilder.append(" --ignore-table=").append("java_sport_recovery.backup");
stringBuilder.append(" --result-file=").append(url).append(" --default-character-set=utf8 ")
.append("java_sport_recovery");
try {
//调用外部执行exe文件的javaAPI
Process process = Runtime.getRuntime().exec(stringBuilder.toString());
if (process.waitFor() == 0) {// 0 表示线程正常终止。
Backup backup = new Backup();
backup.setCreatedAt(new Date());
backup.setName("backup_" + times + ".sql");
backup.setUrl(savePath);
backupMapper.insert(backup);
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@ApiOperation("恢复")
@GetMapping("/recover")
public HttpResult recover(@RequestParam("id") Integer id) {
Backup backup = backupMapper.selectById(id);
if(backup.getStatus().equals(2)) return HttpResult.error("此备份为终止备份数据,不可恢复");
String filepath = backup.getUrl() + backup.getName();
String stmt1 = "mysqladmin -h " + "127.0.0.1" + " -u" + "root" + " -p" + "root" + " create " + "java_sport_recovery";
String stmt2 = "mysql -h " + "127.0.0.1" + " -u" + "root" + " -p" + "root" + " " + "java_sport_recovery" + " < " + filepath;
String[] cmd = {"cmd", "/c", stmt2};
try {
Runtime.getRuntime().exec(stmt1);
Runtime.getRuntime().exec(cmd);
System.out.println("数据已从 " + filepath + " 导入到数据库中");
} catch (IOException e) {
e.printStackTrace();
return HttpResult.error();
}
return HttpResult.ok();
}