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();
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);
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;
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");
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);
}
}
|