JAVA 实现数据库备份(支持远程数据库)

package com.gaxf.paas.task;

import com.gaxf.paas.utils.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.*;

@Component
public class DatabaseTask {
    private static final Logger log = LoggerFactory.getLogger(DatabaseTask.class);
    private static final String PORT = ""; // 数据库端口
    private static final String HOST_IP = ""; // 数据库服务器所在ip 支持远程的 前提是本地服务器上有mysqldump 命令
    private static final String USERNAME = ""; //数据库登录名称
    private static final String PASSWORD = ""; // 数据库登录密码
    private static final String SAVE_PATH_WINDOWS = "D:\\database\\"; // 备份文件存储在本地的路径 windosw 服务器
    private static final String SAVE_PATH_LINUX = "/data/database/"; // 备份文件存储在本地的路径 linux 服务器


    // ======================== 所需要备份的数据库 ============================================
    private static final String JIMI_HYDRANT = "jimi-hydrant";
    private static final String PAAS = "paas";


    /**
     * 数据库备份
     */
    @Scheduled(cron = "0 0 3 * * ?")
    public void dbBackUpPaas() {
        try {
            dbBackUp(PAAS);
            dbBackUp(JIMI_HYDRANT);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param databaseName 需要备份的数据库的名称
     * @return
     */
    public static void dbBackUp(String databaseName) throws Exception {
        String fileName = databaseName + "_" + 当前日期 + ".sql";
        File saveFile = new File(savePath());
        if (!saveFile.exists()) {// 如果目录不存在
            saveFile.mkdirs();// 创建文件夹
        }

        PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(savePath() + fileName), "utf8"));
        Process process = Runtime.getRuntime().exec(getCommand(fileName, databaseName));
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream(), "utf8"));
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            printWriter.println(line);
        }
        printWriter.flush();
        if (process.waitFor() != 0) {
            log.info("数据库备份失败!");
        }
    }

    public static String getCommand(String fileName, String databaseName) {
        StringBuilder arg = new StringBuilder();
        arg.append("mysqldump ");
        arg.append(" -h" + HOST_IP);
        arg.append(" -P" + PORT);
        arg.append(" -u" + USERNAME);
        arg.append(" -p" + PASSWORD);
        arg.append(" --skip-opt ");
        arg.append("--add-drop-database ");
        arg.append("--routines ");
        arg.append("--triggers ");
        arg.append("--compress ");
        arg.append("-r");
        arg.append(savePath());
        arg.append(fileName);
        arg.append(" --databases " + databaseName);
        log.info(arg.toString());
        return arg.toString();
    }

    /**
     * 构建存储sql脚本的路径
     *
     * @return
     */
    public static String savePath() {
        String savePath;
        if (isWindows()) {
            savePath = SAVE_PATH_WINDOWS;
        } else {
            savePath = SAVE_PATH_LINUX;
        }
        return savePath;
    }

    /**
     * 判断服务所在系统为什么操作系统
     *
     * @return
     */
    public static boolean isWindows() {
        return System.getProperty("os.name").toLowerCase().contains("windows");
    }
}

你可能感兴趣的:(java工具类)