try {
String backupDir = null;
StringBuilder buf = null;
File file;
backupDir = RuoYiConfig.getBackupDir();
if(SystemUtils.IS_OS_WINDOWS){
buf = new StringBuilder("mysqldump -q ");
}else {
File file1 = new File("/usr/bin/mysqldump");
File file2 = new File("/usr/local/mysql/bin/mysqldump");
if (file1.exists()) {
buf = new StringBuilder("/usr/bin/mysqldump -q ");
} else if (file2.exists()) {
buf = new StringBuilder("/usr/local/mysql/bin/mysqldump -q ");
} else {
throw new IllegalStateException("cannot find mysqldump");
}
}
file = new File(backupDir);
if (!file.exists()) {
boolean fileStatus = file.mkdir();
if(!fileStatus){
throw new GlobalException("数据库备份目录创建失败");
}
}
DataSourceDTO dataSourceDTO = getGameDb(serverId,"1");//获取数据库信息
buf.append("-u ").append(dataSourceDTO.getUsername());
buf.append(" -h ").append(dataSourceDTO.getHost());
// buf.append(" -p").append(dataSourceDTO.getPassword());
buf.append(" -P ").append(dataSourceDTO.getPort());
buf.append(" --opt ").append(dataSourceDTO.getPoolName());
buf.append(" > ").append(backupDir).append(File.separator);
String backupDbFileName = String.valueOf(serverId) + "_" + dataSourceDTO.getPoolName() + "_" + DateUtil.today()+ ".sql";
buf.append(backupDbFileName);
String cmd = buf.toString();
ArrayList<String> envList = new ArrayList<>();
Map<String,String> map = System.getenv();
Set<Map.Entry<String,String>> entries = map.entrySet();
for (Map.Entry<String, String> entry : entries) {
envList.add(entry.getKey() + "=" + entry.getValue());
}
envList.add("MYSQL_PWD=" + dataSourceDTO.getPassword());
String[] envs = envList.toArray(new String[0]);
Process p = null;
if (SystemUtils.IS_OS_WINDOWS) {
p = Runtime.getRuntime().exec(new String[] { "cmd", "/c", cmd }, envs);
} else {
p = Runtime.getRuntime().exec(new String[] { "sh", "-c", cmd }, envs);
}
int result = p.waitFor();
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
System.out.print(p.getOutputStream());
if (result != 0) {
String msg = "backup game server " + serverId + " FAIL, code=" + result;
throw new IllegalStateException(msg);
}
String backupFileName = backupDir + File.separator + backupDbFileName;
File backupFile = new File(backupFileName);
if (!backupFile.exists()) {
String msg = "backup game server " + serverId + " FAIL, cannot find backup file " + backupDbFileName;
throw new IllegalStateException(msg);
}
}catch (Exception exception){
throw new GlobalException(exception.getMessage());
}