SpringBoot -- 定时任务(定时备份,手动备份,恢复备份)

 

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();
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1. 添加依赖 在pom.xml文件中添加mybatis-plus和quartz依赖: ```xml <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.3.2</version> </dependency> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.3.2</version> </dependency> ``` 2. 配置数据源和mybatis-plus 在application.yml中添加数据源和mybatis-plus的配置: ```yaml spring: datasource: url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false username: root password: root # mybatis-plus配置 mybatis-plus: # mapper文件的位置 mapper-locations: classpath*:mapper/**/*.xml # 配置全局主键策略 global-config: db-config: id-type: auto ``` 3. 编写定时任务 创建一个定时任务类,继承QuartzJobBean,重写executeInternal方法,实现具体的定时任务逻辑。 ```java @Component public class MyTask extends QuartzJobBean { @Override protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException { // TODO: 定时任务逻辑 } } ``` 4. 配置定时任务SpringBoot启动类中添加@EnableScheduling注解,开启定时任务。 ```java @SpringBootApplication @EnableScheduling public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 在定时任务类中添加@Scheduled注解,配置定时任务的执行周期。 ```java @Component public class MyTask extends QuartzJobBean { @Scheduled(cron = "0 0 0 * * ?") @Override protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException { // TODO: 定时任务逻辑 } } ``` 5. 配置定时任务调度器 在SpringBoot启动类中添加一个定时任务调度器的Bean,配置定时任务的调度规则。 ```java @SpringBootApplication @EnableScheduling public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Bean(name = "myTaskJobDetail") public JobDetail myTaskJobDetail() { return JobBuilder.newJob(MyTask.class).withIdentity("myTaskJob").storeDurably().build(); } @Bean(name = "myTaskTrigger") public Trigger myTaskTrigger() { return TriggerBuilder.newTrigger().forJob(myTaskJobDetail()) .withIdentity("myTaskTrigger") .withSchedule(CronScheduleBuilder.cronSchedule("0 0 0 * * ?")) .build(); } } ``` 在定时任务类中不再需要添加@Scheduled注解,因为定时任务已经通过调度器配置好了执行规则。 6. 测试定时任务 在MyTask的executeInternal方法中添加一些测试代码,验证定时任务是否能够正常执行。 ```java @Component public class MyTask extends QuartzJobBean { @Override protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException { System.out.println("定时任务执行了!"); } } ``` 启动SpringBoot应用,等待到定时任务执行时间点,查看控制台输出是否有"定时任务执行了!"日志。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值