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 {
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);
}
}



