springboot对数据库进行备份+对一个文件夹内的文件按时间排序,只保留最近的8个文件

首先,对数据库进行备份,用到的命令:

mysqldump --opt -h 192.168.1.200 --user=root --password=xxx --result-file=E://data//20240911141400.sql --default-character-set=utf8 xxx(数据库名)

直接上代码

配置文件部分代码

代码部分两个类

复制代码
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Component
public class BackUpDataBaseManager {
    @Value("${spring.datasource.driver-class-name}")
    private String driverClassName;
    @Value("${spring.datasource.url}")
    private String url;
    @Value("${spring.datasource.username}")
    private String userName;
    @Value("${spring.datasource.password}")
    private String password;
    @Value("${data.url}")
    private String sqlPath;

    /**
     * 获取数据库名
     */
    public String getDataBaseName() {
        return url.substring(url.indexOf("3306"), url.indexOf("?")).replaceAll("/", "").replaceAll("3306", "");
    }

    /**
     * 获取主机地址
     */
    private String getHost() {
        return url.substring(url.indexOf("mysql"), url.indexOf("3306")).replace(":", "").replace("//", "").replace("mysql", "");
    }

    /**
     * 导出 sql 并返回相关信息
     */
    public void exportSql(String time) {
        // 指定导出的 sql 存放的文件夹
        File saveFile = new File(sqlPath);
        if (!saveFile.exists()) {
            saveFile.mkdirs();
        }
        String host = getHost();
        String dataBaseName = getDataBaseName();
        //创建当月的文件夹
        String fileName = time + ".sql";
        StringBuilder sb = new StringBuilder();
        // 拼接备份命令
        sb.append("mysqldump").append(" --opt").append(" -h ").append(host).append(" --user=").append(userName).append(" --password=").append(password);
        sb.append(" --result-file=").append(sqlPath + fileName).append(" --default-character-set=utf8 ").append(dataBaseName);
        try {
            System.out.println("执行语句:" + sb.toString());
            Process exec = Runtime.getRuntime().exec(sb.toString());
            if (exec.waitFor() == 0) {
                //删除前期的文件
                this.deleteDir();
                System.out.println("数据库备份成功,保存路径:" + sqlPath);
            } else {
                System.out.println("process.waitFor()=" + exec.waitFor());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            System.out.println("备份 数据库 出现 线程中断异常 ");
        } catch (Exception e) {
            System.out.println("备份 数据库 出现 其他异常 ");
        }
    }

    /**
    * @Description: 循环文件夹下的文件,删除指定的文件
    * @param
    * @author zlw
    * @date 2024/9/11 11:21
    */
    public void deleteDir() {
        // 替换为你的文件夹路径
        String folderPath = sqlPath;
        // 要保留的最新文件数量
        int numberToKeep = 8;

        File folder = new File(folderPath);
        File[] files = folder.listFiles();

        if (files != null) {
            List<File> fileList = Arrays.asList(files);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            //list倒序排列
            fileList.sort((f1, f2) -> {
                Date d1 = null;
                Date d2 = null;
                try {
                    d1 = sdf.parse(extractDateTime(f1.getName()));
                    d2 = sdf.parse(extractDateTime(f2.getName()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return d1.compareTo(d2);
            });
            System.out.println("fileList的数据是"+fileList);
            for (int i = 0; i < fileList.size() - numberToKeep; i++) {
                fileList.get(i).delete();
            }
        }
    }

    private static String extractDateTime(String fileName) {
        // 假设文件名的前14个字符包含日期时间信息
        return fileName.length() >= 14 ? fileName.substring(0, 14) : "";
    }
}

定时任务的类

复制代码
public class ScheduledTasks {

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
    @Autowired
    private BackUpDataBaseManager backUpDataBaseManager;

    /**
     * 每天下午4点50分30秒执行
     */
    // 每一分钟执行一次
//     @Scheduled(cron = "0 0/1 * * * ? ")
    //每周三和周日上午9点执行去备份数据库
     @Scheduled(cron = "0 0 9 ? * WED,SUN")
    public void reportCurrentTime() {
        String format = dateFormat.format(System.currentTimeMillis());
        System.out.println("The time is now {}"+format);
        backUpDataBaseManager.exportSql(format);
    }

}

执行结果:

会定时删除一个月前的数据,只保留最近一个月的数据库备份文件

相关推荐
Hrain-AI3 小时前
多 Agent 并行不打架:worktree 隔离与反馈回流落地(附脚本)
网络·数据库·人工智能·架构
净水深流4 小时前
中央厨房冷链技术实践:多温区改造、WMS落地与IoT温控架构
大数据·数据库·人工智能·冷库冷链
l1t4 小时前
测试DuckDB 2.1的match_recognize模式匹配语句
数据库·duckdb
IpdataCloud5 小时前
AI智能体调用工具怎么核验来源IP?归属地、网络类型与代理风险识别(含Python代码)
数据库·python·tcp/ip
曹牧5 小时前
Java:SQL 注入漏洞
数据库
程序员JerrySUN6 小时前
Jetson Edge AI 实战01:Nano、Xavier、Orin 怎么选?Jetson 硬件选型详解【视频讲解】
java·数据库·redis·安全·mybatis
oradh6 小时前
Oracle Undo问题总结(ORA-600 [4xxx] 系列错误)
数据库·oracle
达梦数据6 小时前
DMDRS辅助表生成规则与作用
数据库·oracle
‎ദ്ദിᵔ.˛.ᵔ₎6 小时前
MySQL 表约束
数据库·mysql
Doris__HE7 小时前
【元脑服务器NF5476G7-NF5476M7技术规格分享】
运维·服务器·网络·数据库·性能优化