目录

java-实现数据库备份

目录

java 实现数据库备份

https://img-home.csdnimg.cn/images/20240715101418.png

关键词由CSDN通过智能技术生成

import com.guangyi.project.model.system.DataBaseInFo;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.time.LocalDate;


public class DatabaseTool {

    /**
     * 备份数据库 ,控制台执行命令格式 "mysql的bin目录/mysqldump --databases  -h主机ip -P端口  -u用户名 -p密码  --default-character-set=字符集  数据库名
     *
     * @param mysqlPath  mysql路径
     * @param mysqlIp    mysql主机ip
     * @param mysqlPort  端口
     * @param userName   用户名
     * @param password   密码
     * @param database   数据库名
     * @param resultFile 备份文件全路径
     */
    public static void backup(String mysqlPath, String mysqlIp, String mysqlPort, String userName, String password, String database, String resultFile) {

        InputStream in = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        FileOutputStream fout = null;
        OutputStreamWriter writer = null;
        try {
            Runtime rt = Runtime.getRuntime();
            // 调用mysql的安装目录的命令
            Process process = rt.exec("\"" + mysqlPath + File.separator + "mysqldump\" --databases -h" + mysqlIp + " -P" + mysqlPort + " -u" + userName + " -p" + password
                    + " --add-drop-database --default-character-set=utf8 " + database + " --result-file=" + resultFile);
            // 设置导出编码为utf-8。这里必须是utf-8
            in = process.getInputStream();// 控制台的输出信息作为输入流
            ErrorStreamThread errStream = new ErrorStreamThread(process.getErrorStream()); //错误流另开线程,不然会阻塞
            errStream.start();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (writer != null) {
                    writer.close();
                }
                if (fout != null) {
                    fout.close();
                }
                if (br != null) {
                    br.close();
                }
                if (isr != null) {
                    isr.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
import com.guangyi.project.config.BDException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class ErrorStreamThread extends Thread {

    private InputStream input; // 控制台errorStream

    public ErrorStreamThread(InputStream input) {
        this.input = input;
    }

    @Override
    public void run() {
        InputStreamReader isr = null;
        BufferedReader buff = null;

        try {
            isr = new InputStreamReader(input);
            buff = new BufferedReader(isr);
            String line;
            while ((line = buff.readLine()) != null) {
                if (line.indexOf("Warning") != 0) {
                    throw new Exception(line);
                }
            }
        } catch (Exception e) {
            throw new BDException("错误流线程方法异常", e);
        } finally {
            try {
                if (buff != null) {
                    buff.close();
                }
                if (isr != null) {
                    isr.close();
                }
            } catch (IOException e) {
                throw new BDException("错误流线程方法异常", e);
            }
        }
    }
}

再写个定时任务 每天备份

@Scheduled(cron = "0 0 23 * * ?")
    public void job4() {
        try {
            //备份当天数据库
            DatabaseTool.backup(DataBaseInFo.MYSQL_PATH,DataBaseInFo.MYSQL_IP,DataBaseInFo.MYSQL_PORT,DataBaseInFo.USER_NAME,DataBaseInFo.PASSWORD,DataBaseInFo.DATABASE,DataBaseInFo.RESULT_FILE+LocalDate.now()+"-tianyi.sql");

            //删除7天前的备份
            LocalDate localDate = DateUtils.date2LocalDate(DateUtils.getBeforeDate(new Date(), -8));
            File file = new File(DataBaseInFo.RESULT_FILE+localDate+"-tianyi.sql");
            if (file.exists()){
                file.delete();
            }
        }catch (Exception e){
            logger.error(ErrorInfoUtil.getErrorInfo(e));
            throw ExceptionFormatUtil.formatException(e, ErrorEnum.GETINFO_ERROR);
        }
    }