java备份数据库

版权声明: https://blog.csdn.net/qq_36004521/article/details/81481608

我是在SpringBoot项目中写的

1.创建时间管理类 

package com.hontye.Database;

import com.hontye.parameter.util.PropertyFileUtils;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;

/*在 TimerManager 这个类里面,大家一定要注意 时间点的问题。如果你设定在凌晨2点执行任务。但你是在2点以后
        发布的程序或是重启过服务,那这样的情况下,任务会立即执行,而不是等到第二天的凌晨2点执行。为了,避免这种情况
        发生,只能判断一下,如果发布或重启服务的时间晚于定时执行任务的时间,就在此基础上加一天。*/
public class TimerManager {
    //时间间隔 一天时间
    private static final long PERIOD_DAY = 24 * 60 * 60 * 1000;

    public TimerManager() {

        //获取并处理配置文件中的时间
        String backuptime=PropertyFileUtils.get("backuptime");
        String[] time=backuptime.split(":");
        int hours=Integer.parseInt(time[0]);
        int minute=Integer.parseInt(time[1]);
        int second=Integer.parseInt(time[2]);

        Calendar calendar = Calendar.getInstance();

/*** 定制每日2:00执行方法 ***/
        calendar.set(Calendar.HOUR_OF_DAY,hours);
        calendar.set(Calendar.MINUTE, minute);
        calendar.set(Calendar.SECOND, second);

        Date date=calendar.getTime(); //第一次执行定时任务的时间

//如果第一次执行定时任务的时间 小于 当前的时间
//此时要在 第一次执行定时任务的时间 加一天,以便此任务在下个时间点执行。如果不加一天,任务会立即执行。
        if (date.before(new Date())) {
            date = this.addDay(date, 1);
        }

        Timer timer = new Timer();

        NFDFlightDataTimerTask task = new NFDFlightDataTimerTask();
        //安排指定的任务在指定的时间开始进行重复的固定延迟执行。
        timer.schedule(task,date,PERIOD_DAY);
    }

    // 增加或减少天数
    public Date addDay(Date date, int num) {
        Calendar startDT = Calendar.getInstance();
        startDT.setTime(date);
        startDT.add(Calendar.DAY_OF_MONTH, num);
        return startDT.getTime();
    }
}

2.配置监听器

package com.hontye.Database;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

//创建一个监听器
public class NFDFlightDataTaskListener implements ServletContextListener {

    public void contextInitialized(ServletContextEvent event) {
        new TimerManager();
    }

    public void contextDestroyed(ServletContextEvent event) {
    }

}

3.配置监听器

package com.hontye.parameter;

import com.hontye.Database.NFDFlightDataTaskListener;
import com.hontye.parameter.util.PropertyFileUtils;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/*
* 监听器配置
* */

@Configuration
public class ListenerConfig {
    @Bean
    public ServletListenerRegistrationBean servletListenerRegistrationBean(){
        ServletListenerRegistrationBean servletListenerRegistrationBean = new ServletListenerRegistrationBean();
        servletListenerRegistrationBean.setListener(new PropertyFileUtils());
        return servletListenerRegistrationBean;
    }
    @Bean
    public ServletListenerRegistrationBean servletListenerRegistrationBean1(){
        ServletListenerRegistrationBean servletListenerRegistrationBean = new ServletListenerRegistrationBean();
        servletListenerRegistrationBean.setListener(new NFDFlightDataTaskListener());
        return servletListenerRegistrationBean;
    }
}

4.创建执行类,继承TimerTask

package com.hontye.Database;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.TimerTask;

//调用要执行的内容
public class NFDFlightDataTimerTask extends TimerTask {

    private static Logger log = LoggerFactory.getLogger(NFDFlightDataTimerTask.class);
    @Override
    public void run() {
        try {
            new DatabaseBackupUtil();//要执行的内容
} catch (Exception e) {
            log.info("-------------解析信息发生异常--------------");
        }
    }

}

5.编写数据库备份工具类

package com.hontye.Database;

import com.hontye.parameter.util.PropertyFileUtils;
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DatabaseBackupUtil {
    /**
     * Java代码实现MySQL数据库导出
     *
     * @author GaoHuanjie
     * @param hostIP MySQL数据库所在服务器地址IP
     * @param userName 进入数据库所需要的用户名
     * @param password 进入数据库所需要的密码
     * @param savePath 数据库导出文件保存路径
     * @param databaseName 要导出的数据库名
     * @return 返回true表示导出成功,否则返回false。
     */
    private static String hostIP = PropertyFileUtils.get("hostIp");
    private static String userName = PropertyFileUtils.get("spring.datasource.username");
    private static String password = PropertyFileUtils.get("spring.datasource.password");
    private static String savePath = PropertyFileUtils.get("savePath");
    private static String databaseName = PropertyFileUtils.get("databaseName");
    private static String binUrl = PropertyFileUtils.get("binUrl");
        
        public DatabaseBackupUtil() throws InterruptedException {
            // 备份数据库
            if(exportDatabaseTool()){
                System.out.println("备份数据库成功!");
            }
        }

    public static boolean exportDatabaseTool() throws InterruptedException {
        File saveFile = new File(savePath);
        if (!saveFile.exists()) {// 如果目录不存在
            saveFile.mkdirs();// 创建文件夹
        }
        if(!savePath.endsWith(File.separator)){
            savePath = savePath + File.separator;
        }
        PrintWriter printWriter = null;
        BufferedReader bufferedReader = null;
        try {
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
            String fileName = df.format(new Date()) + ".sql";
            printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(savePath+"test.sql"), "utf8"));
            StringBuilder stringBuilder = new StringBuilder();
            if(binUrl != null && !binUrl.equals("")){
                stringBuilder.append(binUrl).append("/");
            }
            stringBuilder.append("mysqldump").append(" --opt").append(" -h").append(hostIP);
            stringBuilder.append(" --user=").append(userName) .append(" --password=").append(password).append(" --lock-all-tables=true");
            stringBuilder.append(" --result-file=").append(savePath+fileName).append(" --default-character-set=utf8 ").append(databaseName).append(" -R");
            String command = stringBuilder.toString();
            Process process = Runtime.getRuntime().exec(command);
            InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream(), "utf8");
            bufferedReader = new BufferedReader(inputStreamReader);
            String line;
            while((line = bufferedReader.readLine())!= null){
                printWriter.println(line);
            }
            printWriter.flush();
            if(process.waitFor() == 0){//0 表示线程正常终止。
                return true;
            }
        }catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
                if (printWriter != null) {
                    printWriter.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

}

猜你喜欢

转载自blog.csdn.net/qq_36004521/article/details/81481608
今日推荐