记录在Linux 系统上定时备份MySQL数据库
1、在代码中添加备份
package org.jeecg.modules.xczxhhr.job;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;
@Slf4j
public class SyncDatabaseBackupJob implements Job {
@Override
public void execute(JobExecutionContext jobExecutionContext) {
String mysqlUser = "root";
String mysqlPassword = "你的密码";
String dbname = "你的数据库名字";
String backupDir = "备份文件存储地址";
int expireDays = 15;
String backupTime = new SimpleDateFormat("yyyyMMddHHmm").format(new Date());
String backupFileName = dbname + "-" + backupTime + ".sql";
String[] command = new String[]{"mysqldump", "-u" + mysqlUser, "-B", dbname};
ProcessBuilder processBuilder = new ProcessBuilder(command);
processBuilder.environment().put("MYSQL_PWD", mysqlPassword);
File backupFile = new File(backupDir, backupFileName);
processBuilder.redirectOutput(backupFile);
try {
Process process = processBuilder.start();
int exitStatus = process.waitFor();
if (exitStatus == 0) {
// 备份成功,可以继续实现删除过期备份的逻辑
log.info("数据库备份成功");
cleanupOldBackups(backupDir, expireDays);
} else {
// 备份失败,可以记录日志或者进行其他处理
log.error("数据库备份失败:" + exitStatus);
// 输出错误信息
BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
String line;
while ((line = errorReader.readLine()) != null) {
log.error(line);
}
}
} catch (IOException | InterruptedException e) {
// 异常处理
e.printStackTrace();
log.error("备份数据库出现异常:" + e.getMessage());
}
}
private void cleanupOldBackups(String backupDir, int expireDays) {
File dir = new File(backupDir);
File[] files = dir.listFiles();
if (files != null) {
for (File file : files) {
long diffInMillies = System.currentTimeMillis() - file.lastModified();
long diffInDays = TimeUnit.DAYS.convert(diffInMillies, TimeUnit.MILLISECONDS);
if (diffInDays > expireDays) {
if (file.delete()) {
log.info("已删除旧备份文件:" + file.getName());
} else {
log.info("未能删除旧备份文件:"+ file.getName());
}
}
}
}
}
}
2、也可以在Linux中执行备份脚本,backup_script
.sh,内容如下:
#!/bin/bash
# 设置mysql的登录用户名和密码(根据实际情况填写)
mysqlUser="root"
mysqlPassword="密码"
dbname='数据库名字'
# 备份文件存放地址(根据实际情况填写)
backup_dir=/data/depFile/bakdb
# 判断目录是不是已经存在,如果不存在则创建
if [ ! -d $backup_dir ]; then
mkdir -p $backup_dir
fi
#===================================
# 是否删除过期数据
expire_backup_delete="ON"
expire_days=15
backup_time=$(date +%Y%m%d%H%M)
welcome_msg="Welcome to use MySQL backup tools!"
#===========================================
# 备份指定数据库中数据(此处假设数据库是mysql_backup_test)
mysqldump -u$mysqlUser -p$mysqlPassword -B $dbname >$backup_dir/$dbname-$backup_time.sql
#删除过期数据
if [ "$expire_backup_delete" == "ON" -a "$backup_dir" != "" ]; then
# $(find $backup_dir/ -type f -mtime +$expire_days | xargs rm -rf)
find $backup_dir/ -type f -mtime +$expire_days -exec rm -f {} \;
echo "Expired backup data delete complete!"
fi
接下来,你需要设置一个定时任务,让这个脚本在每天凌晨一点执行。你可以使用 cron 来实现这一点。
首先,打开终端并输入以下命令来编辑 crontab 文件:
crontab -e
然后,在 crontab 文件中添加以下行来设置定时任务:
0 1 * * * /bin/bash /path/to/your/backup_script.sh
在这个例子中,/path/to/your/backup_script.sh
应该替换为你实际的备份脚本所在的路径。
保存并退出编辑器,这样就设置好了定时任务。这个任务将会在每天凌晨一点执行你的备份脚本