概要
Springboot執(zhí)行shell命令備份數(shù)據(jù)庫。
1、查看mysql版本
mysql --version
文章來源:http://www.zghlxwxcb.cn/news/detail-727956.html
2、相關(guān)依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.20</version>
</dependency>
3、具體代碼
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.time.LocalDate;
import org.springframework.core.io.ResourceLoader;
@Component
@Slf4j
public class BackupJob {
//數(shù)據(jù)庫連接地址
@Value("${spring.datasource.url}")
private String dbUrl;
//數(shù)據(jù)庫名
@Value("${spring.datasource.name}")
private String dbName;
//用戶名
@Value("${spring.datasource.username}")
private String dbUserName;
//密碼
@Value("${spring.datasource.password}")
private String dbPassWord;
//存放路徑
@Value("${backup.path}")
private String filePath;
// 在你的類中注入ResourceLoader,用來獲取備份的sql文件
@Autowired
private ResourceLoader resourceLoader;
/**
* 數(shù)據(jù)庫版本是否為 8.0 + (false=否 true=是), mysql8+ 需要參數(shù) --column-statistics=0 , mysql8- 不需要
* 新版的mysqldump默認(rèn)啟用了一個(gè)新標(biāo)志,通過--column-statistics=0來禁用
*/
boolean isDbVersion8 = true;
@SneakyThrows
public void backup() {
log.info("【備份數(shù)據(jù)庫】--START");
String dbUrl2 = dbUrl.replace("jdbc:mysql://", "");
// 獲取數(shù)據(jù)庫地址
String[] serverPath = dbUrl2.substring(0, dbUrl2.indexOf("/")).split(":");
String ip = serverPath[0];
String port = serverPath[1];
// 數(shù)據(jù)庫賬號
String username = dbUserName;
// 數(shù)據(jù)庫密碼
String password = dbPassWord;
String dbParam = "";
// 備份文件目錄+名稱 備份文件存放目錄+名稱(名稱 = 數(shù)據(jù)庫名+時(shí)間字符串.sql)
String timeStr = LocalDate.now().toString();
String pathFileName = filePath + dbName + "_" + timeStr + ".sql";
String newCmd = "mysqldump -h{SERVER-PATH} -P{SERVER-PORT} -u{USERNAME} -p{PASSWORD} {DBNAME} {DB-PARAM} > {FILEPATH}";
if(isDbVersion8){
dbParam = "--column-statistics=0";
}
// 執(zhí)行命令
newCmd = newCmd.replace("{USERNAME}", username)
.replace("{PASSWORD}", password)
.replace("{SERVER-PATH}", ip)
.replace("{DBNAME}", dbName)
.replace("{SERVER-PORT}", port)
.replace("{FILEPATH}", pathFileName)
.replace("{DB-PARAM}", dbParam);
//這里打印出來的命令是可以直接在 終端執(zhí)行的。
System.out.println(newCmd);
System.out.println(pathFileName);
// 創(chuàng)建進(jìn)程構(gòu)建器
ProcessBuilder processBuilder = new ProcessBuilder();
// 設(shè)置命令和參數(shù)
processBuilder.command(getOsShell(), "-c" , newCmd);
// processBuilder.command(getOsShell(), "/c" , newCmd);
// 啟動(dòng)進(jìn)程
Process process = processBuilder.start();
// 獲取命令執(zhí)行的輸出流
InputStream inputStream = process.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
// 讀取輸出
String line;
while ((line = reader.readLine()) != null) {
log.info(line);
}
// 等待命令執(zhí)行完成
int exitCode = process.waitFor();
System.out.println("命令執(zhí)行完成,退出碼:" + exitCode);
if (exitCode == 0) {
log.info("數(shù)據(jù)庫備份成功!");
} else {
log.info("數(shù)據(jù)庫備份失??!");
}
//TODO 獲取文件備份的文件、上傳到云服務(wù)。
// Resource resource = resourceLoader.getResource("file:" + pathFileName);
// InputStream inputStream = resource.getInputStream();
// byte[] bytes = IoUtil.readBytes(resource.getInputStream());
//TODO 同步備份記錄到數(shù)據(jù)庫
//TODO 刪除指定文件
// FileUtil.del(pathFileName);
}
public String getOsShell() {
String osName = System.getProperty("os.name");
// TODO Windows未測試
if (osName.toLowerCase().contains("windows")) {
return "cmd.exe";
} else if (osName.toLowerCase().contains("mac")) {
return "/bin/bash";
} else if (osName.toLowerCase().contains("linux")) {
return "/bin/bash";
}
return "";
}
}
技術(shù)細(xì)節(jié)
主要就是使用ProcessBuilder創(chuàng)建系統(tǒng)進(jìn)程,執(zhí)行終端命令。文章來源地址http://www.zghlxwxcb.cn/news/detail-727956.html
到了這里,關(guān)于Springboot使用ProcessBuilder創(chuàng)建系統(tǒng)進(jìn)程執(zhí)行shell命令備份數(shù)據(jù)庫的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!