1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
/**
* @Description: TODO
* @Author: luis_liu
* @DateTime: 2021/6/29 9:55
*/
public class MysqlDumpMethod {
private static final String dirName = "文件夹name";
private static final String userDir = System.getProperty("user.dir");
private static final String mysqldumpPath = "mysqldump绝对路径";
private static final String fileAbsPath = userDir + File.separator + dirName + File.separator;
private static final String sysLineSeparator = System.getProperty("line.separator");
private static final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

/**
* 获取所有符合条件需要导出的entity
*
* @return List<JSONObject>
*/
public static List<JSONObject> getAllExportEntity() {
//
}

/**
* getExportDumpBat
*
* @param allExportEntity
* @param tenant
*/
public static void getExportDumpBat(List<JSONObject> allExportEntity) {
Runtime runtime = Runtime.getRuntime();
Process process = null;
List<File> fileResultList = new ArrayList<>();
StringBuilder sqlExportSb = new StringBuilder();
File dirFile = new File(userDir + File.separator + dirName);
if (!dirFile.exists()) {
dirFile.mkdirs();
}
for (JSONObject entity : allExportEntity) {
JSONObject module = entity.getJSONObject("module");
String dbName = module.getString("dbName");
if (StringUtils.isNotEmpty(dbName)) {
if (ymlData != null) {
sqlExportSb.append(isWinOs ? "mysqldump" : mysqldumpPath);
sqlExportSb.append(" --extended-insert=false"); // 解决生成的Sql文件只有一条insert语句
sqlExportSb.append(" -u").append(user);
sqlExportSb.append(" -p").append(password);
sqlExportSb.append(" -h").append(host);
sqlExportSb.append(" -P").append(port);
sqlExportSb.append(" --default-character-set=").append("utf8");
sqlExportSb.append(" --databases");
sqlExportSb.append(" ").append(dbName);
// entityResult 导出的table名集合
if (!entityResult.isEmpty()) {
sqlExportSb.append(" --tables ");
for (JSONObject entityRe : entityResult) {
sqlExportSb.append(entityRe.getString("tableName")).append(" ");
}
// where过滤数据
sqlExportSb.append(" --where ");
sqlExportSb.append("\"xxx='").append(tenant.getId()).append("'\"");
}
String filePath = fileAbsPath + dbName.replace(" _ ", " ") + ".sql";
sqlExportSb.append(" > ").append(filePath);
sqlExportSb.append(sysLineSeparator);
fileResultList.add(new File(filePath));
}
}
}
File batFile = createBAT(sqlExportSb.toString(), "sqlDataExport");
try {
String canonicalPath = batFile.getCanonicalPath();
process = isWinOs ? runtime.exec(new String[]{"cmd", "/c", canonicalPath}) :
runtime.exec(new String[]{"/bin/bash", canonicalPath});
new ProcessClearStream(process.getInputStream(), "INFO").start();
new ProcessClearStream(process.getErrorStream(), "ERROR").start();
boolean isSuccess = process.waitFor(20, TimeUnit.SECONDS);
System.out.println("finish run cmd----------------------->");
if (isSuccess) {
fileResultList.add(batFile);
fileResultList.add(sqlDataImportFile);
toZip(fileResultList, tenant);
} else {
throw new CommonException("错误", "响应超时,或执行失败");
}
} catch (Exception e) {
throw new CommonException("错误", e.getMessage());
} finally {
if (null != process) {
process.destroy();
}
}
}


/**
* 压缩成zip
*
* @param sqlFiles
* @param tenant
* @throws RuntimeException
* @throws IOException
*/
public static void toZip(List<File> sqlFiles, Tenant tenant) {
FileOutputStream fos1;
try {
fos1 = new FileOutputStream(fileAbsPath + tenant.getCode() + "-" + simpleDateFormat.format(new Date()) + ".zip");
try (ZipOutputStream zipOutputStream = new ZipOutputStream(fos1)) {
for (File srcFile : sqlFiles) {
byte[] buf = new byte[BUFFER_SIZE];
zipOutputStream.putNextEntry(new ZipEntry(srcFile.getName()));
int len;
FileInputStream in = new FileInputStream(srcFile);
while ((len = in.read(buf)) != -1) {
zipOutputStream.write(buf, 0, len);
}
zipOutputStream.closeEntry();
in.close();
}
deleteFile(sqlFiles);
} catch (Exception e) {
throw new CommonException("错误", e.getMessage());
}
} catch (FileNotFoundException e) {
throw new CommonException("错误", e.getMessage());
}
}

/**
* 删除文件
*
* @param sqlFiles
*/
public static void deleteFile(List<File> sqlFiles) {
for (File file : sqlFiles) {
// 如果文件路径所对应的文件存在,并且是一个文件,则直接删除
if (file.exists() && file.isFile()) {
try {
file.delete();
} catch (Exception e) {
throw new CommonException("错误", e.getMessage());
}
}
}
}

/**
* 创建bat文件
*
* @param command
* @return
*/
private static File createBAT(String command, String fileName) {
File file = new File(fileAbsPath + fileName + (isWinOs ? ".bat" : ".sh"));
try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
writer.write(command);
writer.flush();
} catch (Exception e) {
throw new CommonException("错误", e.getMessage());
}
return file;
}
}