mysql在centos下自动备份可使用脚本来实现,但是密码必须写在脚本中,若是直接在java定时任务代码中实现备份,百度出来的方案多数不太靠谱,踏过无数的坑后,这里共享一个实际使用中的代码。
public static void backup(String DB_USER, String DB_PWD, String DB_NAME, String BACKUP_DIR) {
String savePath = new File(BACKUP_DIR, DB_NAME + "_" + df.format(new Date()) + ".sql").getAbsolutePath();
String sql = "/usr/bin/mysqldump -u" + DB_USER + " -p" + DB_PWD + " " + DB_NAME + " >" + savePath;
String cmd[] = {"/usr/bin/sh", "-c", sql};
Process process;
try {
process = Runtime.getRuntime().exec(cmd);
int processComplete = process.waitFor();
if (processComplete == 0) {
logger.info("备份成功: " + savePath);
} else {
logger.error("备份失败: " + savePath);
}
} catch (InterruptedException e) {
logger.error("备份失败: " + savePath + "\r\n" + e.getMessage());
e.printStackTrace();
} catch (IOException e) {
logger.error("备份失败: " + savePath + "\r\n" + e.getMessage());
e.printStackTrace();
}
}