import java.io.File; import java.util.Date; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import com.ibm.icu.text.SimpleDateFormat; @Configuration //1.主要用于标记配置类,兼备Component的效果。 @EnableScheduling public class MysqlUtil { @Value("${spring.datasource.ip}") private String mysqlIp;// mysql主机ip @Value("${spring.datasource.port}") private String mysqlPort;//端口 @Value("${spring.datasource.username}") private String userName;//用户名 @Value("${spring.datasource.password}") private String password;//密码 @Value("${spring.datasource.dataname}") private String database;//数据库名 @Value("${spring.datasource.filepath}") private String filePath; private static final SimpleDateFormat yearMonthDayFormat = new SimpleDateFormat("yyyy-MM-dd"); @Scheduled(cron="0/20 * * * * ?") public void statisticTasks() { //备份文件全路径 //String dateString = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()); if(!new File(filePath).exists()){ new File(filePath).mkdir(); } String resultFile =filePath+ File.separator + mysqlIp +"_"+ database +".sql"; new File(resultFile).delete(); try { String cmd = "docker exec -it mysql mysqldump -h"+mysqlIp+" -P"+mysqlPort+" -u"+ userName +" -p"+password+" "+database + ">" + resultFile; System.out.println("cmd:"+new String[]{"bash", "-c",cmd}.toString()); Process process=Runtime.getRuntime().exec(new String[]{"bash", "-c",cmd}); if(process==null){ System.err.println(process.getErrorStream()); process.getErrorStream(); } } catch (Exception e) { e.printStackTrace(); } }
}
数据库:mysql 位置:docker 容器 所以增加 docker exec -it mysql 因为可能是远程数据库:所以增加 -h 和-P 用于标识 地址和端口号
直接执行Runtime.getRuntime.exec(cmd)时 一直不能生成sql语句,也不报错,但是在linux远程界面上直接执行可以生成sql语句,
所以应该是在程序中执行的语句有问题。
一开始以为是权限问题,更改了文件夹的权限还是生成不了。
百度说是cmd中存在空格的问题,后面执行了cmd.replaceAll(" ","\" \"")在执行就直接报错了 遂放弃
后面说加上"bash" "-c"并用字符串数组的形式进行执行 果然生成了sql,和权限没有关系,
百度了 bash -c 意思是执行命令时用 bash shell来执行命令,可能是linux系统没有默认或者怎样吧。
bash是shell的一种 shell是充当人与计算机之间的翻译官,用来把命令翻译成计算机识别的二进制文件。
一开始没有生成sql可能是cmd中存在空格等字符,空格在linux系统有特殊含义,所以解析成不是计算机可以识别的命令吧。故而没有生成sql语句。
原文:https://www.cnblogs.com/xiatc/p/12376952.html