import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.File;
import java.time.LocalDateTime;
/**
* @author :jerry
* @date :Created in 2022/11/10 19:14
* @description:
* @version: V1.1
*/
public class DbBaseController {
private static String backupPath="/Users/jerry/fsdownload"; //保存文件目录
private static String dataName="test"; //数据库名
private static String mysqldumpPath="mysqldump";
private static String username="root"; //数据库用户名
private static String password="123456"; //数据库密码
private static String prot="3306"; //数据库端口
private static String ip="10.17.64.208"; //数据库安装的主机IP
public static void dbBack() {
File file = new File(backupPath);
if (!file.exists()) {
file.mkdirs();
}
String fileName = backupPath + "/" + dataName+System.currentTimeMillis() + ".sql";
/** 默认使用linux*/
//String cmdPrefix = "/bin/sh -c ";
String c1 = "/bin/sh";
String c2 = "-c";
String os_name = System.getProperty("os.name");
// 判断是否是windows系统
if (os_name.toLowerCase().startsWith("win")){
//cmdPrefix = "cmd /c ";
c1 = "cmd";
c2 = "/c";
}
String cmd = mysqldumpPath
+ " -u" + username
+ " -p" + "'" + password + "'"
+ " -h"+ip
+ " -P" + prot
+ " " + dataName
+ " > " + fileName; // 最终写入的文件路径
try {
log.info("数据库备份START" + LocalDateTime.now());
/**
* exec重载方法有一个参数的,window下执行正常,linux下无法完成备份。
* 使用多参数重载方法都可以正常备份
*/
Process process = Runtime.getRuntime().exec(new String[]{c1, c2, cmd});
process.waitFor();
log.info("数据库备份END" + LocalDateTime.now());
} catch (Exception e) {
e.printStackTrace();
log.error("数据库备份失败:{}", e.getMessage());
}
}
public static void main(String[] args) {
dbBack();
}
}
版权声明:本文为qq_40068304原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。