76 lines
2.2 KiB
Java
76 lines
2.2 KiB
Java
package com.tiesheng.database.config;
|
|
|
|
import cn.hutool.core.date.DateUtil;
|
|
import cn.hutool.core.io.FileUtil;
|
|
import cn.hutool.core.util.RuntimeUtil;
|
|
import cn.hutool.core.util.StrUtil;
|
|
import cn.hutool.db.DbUtil;
|
|
import cn.hutool.extra.spring.SpringUtil;
|
|
import cn.hutool.log.LogFactory;
|
|
import com.tiesheng.database.utls.TieshengDbUtil;
|
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
|
import org.springframework.context.annotation.Configuration;
|
|
|
|
import java.util.Date;
|
|
|
|
/**
|
|
* @author hao
|
|
*/
|
|
@Configuration
|
|
@ConfigurationProperties(prefix = "tiesheng.db-backup")
|
|
public class DbBackupConfig {
|
|
|
|
/**
|
|
* 数据库备份的路径
|
|
*/
|
|
private String path = "/root/backup/";
|
|
|
|
/**
|
|
* 备份文件的时间格式
|
|
*/
|
|
private String format = "yyyyMMdd";
|
|
|
|
|
|
/**
|
|
* 数据库备份
|
|
*/
|
|
public void dbBackup() {
|
|
String url = SpringUtil.getProperty("spring.datasource.url");
|
|
String username = SpringUtil.getProperty("spring.datasource.username");
|
|
String password = SpringUtil.getProperty("spring.datasource.password");
|
|
String dbName = TieshengDbUtil.getTableSchema(url);
|
|
|
|
try {
|
|
String saveFile = StrUtil.format("{}{}/{}.sql.gz", getPath(), dbName, DateUtil.format(new Date(), format));
|
|
FileUtil.mkParentDirs(saveFile);
|
|
String cmd = StrUtil.format("mysqldump -u {} --password='{}' --databases {} --compress | gzip -9 > {} ", username, password, dbName, saveFile);
|
|
LogFactory.get().info("cmd: " + cmd);
|
|
String forStr = RuntimeUtil.execForStr(cmd);
|
|
LogFactory.get().info("dbBackup: " + forStr);
|
|
} catch (Exception e) {
|
|
LogFactory.get().info(e);
|
|
}
|
|
|
|
}
|
|
|
|
///////////////////////////////////////////////////////////////////////////
|
|
// setter\getter
|
|
///////////////////////////////////////////////////////////////////////////
|
|
|
|
public String getPath() {
|
|
return path;
|
|
}
|
|
|
|
public void setPath(String path) {
|
|
this.path = path;
|
|
}
|
|
|
|
public String getFormat() {
|
|
return format;
|
|
}
|
|
|
|
public void setFormat(String format) {
|
|
this.format = format;
|
|
}
|
|
}
|