一、RuoYiConfig.class 新增获取备份路径方法
public static String getDataBaseBackUp() {return getProfile() + "/dbBackUp";}
二、RyTask:新增备份数据库方法
mySqlDump方法:参数详见代码
package com.ruoyi.quartz.task;import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ZipUtil;
import cn.hutool.system.OsInfo;
import cn.hutool.system.SystemUtil;
import com.ruoyi.common.config.RuoYiConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;import java.io.File;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;/*** 定时任务调度测试** @author ruoyi*/
@Component("ryTask")
public class RyTask {/**** @param host:数据库Ip* @param port:数据库端口* @param username:数据库账号* @param password:数据库密码* @param databasename:数据库名称* @param backupNumStr:备份保留份数* @throws Exception*/public void mySqlDump(String host, String port, String username, String password, String databasename,String backupNumStr) throws Exception {String dir = RuoYiConfig.getDataBaseBackUp();if (!FileUtil.exist(dir)) {FileUtil.mkdir(dir);}String sqlName = DateUtil.format(new Date(), DatePattern.PURE_DATETIME_MS_PATTERN)+ ".sql";String sqlPathName = dir + File.separator + sqlName;if (FileUtil.exist(sqlPathName)) {System.out.println(sqlName + "文件名已存在,请更换");return;}//拼接cmd命令 windows下 cmd Linux下 /bin/shProcess exec;OsInfo osInfo = SystemUtil.getOsInfo();//如果不能取得系统属性os.name(因为Java安全限制),则总是返回falseif(osInfo.isWindows()){exec = Runtime.getRuntime().exec("cmd /c mysqldump -h" + host + " -P" + port + " -u " + username + " -p" + password + " " + databasename + " > " + sqlPathName);} else {exec = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", "/usr/bin/mysqldump -h" + host + " -P" + port + " -u " + username + " -p" + password + " " + databasename + " > " + sqlPathName});}if (exec.waitFor() == 0) {System.out.println("数据库备份成功,备份路径为:" + sqlPathName);}//压缩String zipPathName = dir + File.separator + sqlName + ".zip";ZipUtil.zip(sqlPathName, zipPathName);//删除FileUtil.del(sqlPathName);//获取外部的备份保留份数int backupNum = 5;try {backupNum = NumberUtil.parseInt(backupNumStr);} catch (Exception e){System.out.println("backupNumStr非数字:"+backupNumStr);}//删除之前备份份数List<String> fileNames = FileUtil.listFileNames(dir);if(CollUtil.isNotEmpty(fileNames)){//从大到小排序fileNames = fileNames.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());for (int i = 0; i < fileNames.size(); i++) {//超过的份数全删除if(i>=backupNum){FileUtil.del(dir + File.separator + fileNames.get(i));}}}}
}
三、配置定时任务
其中7代表:备份保留的份数,默认是5份(假设传入的不能转成数字)
ryTask.mySqlDump('127.0.0.1','3306','数据库账号','数据库密码','数据库','7')
四、执行效果
方法调用hutool压缩方法、文件扫描、删除方法,测试均通过
上传路径都配置的:
/data/项目名(非中文)/uploadPath