zoukankan      html  css  js  c++  java
  • spring boot 定时备份数据库

    第一步 :添加mysqldump.exe 进环境变量

    第二步  新建一个spring boot 项目,连接数据库

    spring.datasource.url=jdbc:mysql://localhost:3308/springbootdb?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true
    spring.datasource.username=root
    spring.datasource.password=mysql
    spring.datasource.driver-class-name=com.mysql.jdbc.Driver

    第三步  添加相关需要的jar

    <dependency>
    	<groupId>mysql</groupId>
    	<artifactId>mysql-connector-java</artifactId>
    	<scope>runtime</scope>
    </dependency>
    <!-- quartz -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-quartz</artifactId>
    </dependency>
    

    第四步 创建定时任务

        /**
         * 执行定时任务
         */
        @Override
        protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
            // TODO Auto-generated method stub
            System.out.println("执行定时任务》》》"+new Date());
            String filePath="D:\数据库文件\";
            String dbName="springbootdb";//备份的数据库名
            String username="root";//用户名
            String password="mysql";//密码
            File uploadDir = new File(filePath);
            if (!uploadDir.exists())
                uploadDir.mkdirs();
            
            String cmd =  "mysqldump -u"+ username +"  -p "+password + dbName + " -r "
                    + filePath + "/" + dbName+new java.util.Date().getTime()+ ".sql";
            try {
            Process process = Runtime.getRuntime().exec(cmd); 
                System.out.println("备份数据库成功!!!");         
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
         
            }
    
        }

    第五步  配置quartz,设置每10秒执行一次定时任务

    @Configuration
    public class QuartzConfig {
        @Bean
        public JobDetail teatQuartzDetail(){
            return JobBuilder.newJob(TestQuartz.class).withIdentity("testQuartz").storeDurably().build();
        }
    
        @Bean
        public Trigger testQuartzTrigger(){
            SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule()
                    .withIntervalInSeconds(10)  //设置时间周期单位秒
                    .repeatForever();
            return TriggerBuilder.newTrigger().forJob(teatQuartzDetail())
                    .withIdentity("testQuartz")
                    .withSchedule(scheduleBuilder)
                    .build();
        }
    
    }

    第六步  运行项目

     备份成功!!!!!!!!!!!!!!!!!!!!

     

    github项目地址    copyDatabase   

  • 相关阅读:
    RPC中阻塞队列的作用
    记用tensorflow-ranking时的bugs
    JDK作泛型比较时为什么把逻辑代码写两遍
    Java 不能声明泛型数组
    QuickSort Hoare vs Lomuto
    Java 对数组扩容
    Java交换两对象的问题
    毕业 失业
    dependencyManagement介绍
    web笔记
  • 原文地址:https://www.cnblogs.com/lick468/p/9807469.html
Copyright © 2011-2022 走看看