案例代码:sprimngboot备份数据库
生活随笔
收集整理的這篇文章主要介紹了
案例代码:sprimngboot备份数据库
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
文章目錄
- 工具類:
- service層:
- 常量:
- controller:
工具類:
public class MySqlBackupRestoreUtils {/*** 備份數(shù)據(jù)庫(kù)* @param host host地址,可以是本機(jī)也可以是遠(yuǎn)程* @param userName 數(shù)據(jù)庫(kù)的用戶名* @param password 數(shù)據(jù)庫(kù)的密碼* @param savePath 備份的路徑* @param fileName 備份的文件名* @param databaseName 需要備份的數(shù)據(jù)庫(kù)的名稱* @return* @throws IOException */public static boolean backup(String host, String userName, String password, String backupFolderPath, String fileName,String database) throws Exception {File backupFolderFile = new File(backupFolderPath);if (!backupFolderFile.exists()) {// 如果目錄不存在則創(chuàng)建backupFolderFile.mkdirs();}if (!backupFolderPath.endsWith(File.separator) && !backupFolderPath.endsWith("/")) {backupFolderPath = backupFolderPath + File.separator;}// 拼接命令行的命令String backupFilePath = backupFolderPath + fileName;StringBuilder stringBuilder = new StringBuilder();stringBuilder.append("mysqldump --opt ").append(" --add-drop-database ").append(" --add-drop-table ");stringBuilder.append(" -h").append(host).append(" -u").append(userName).append(" -p").append(password);stringBuilder.append(" --result-file=").append(backupFilePath).append(" --default-character-set=utf8 ").append(database);// 調(diào)用外部執(zhí)行 exe 文件的 Java APIProcess process = Runtime.getRuntime().exec(getCommand(stringBuilder.toString()));if (process.waitFor() == 0) {// 0 表示線程正常終止System.out.println("數(shù)據(jù)已經(jīng)備份到 " + backupFilePath + " 文件中");return true;}return false;}/*** 還原數(shù)據(jù)庫(kù)* @param restoreFilePath 數(shù)據(jù)庫(kù)備份的腳本路徑* @param host IP地址* @param database 數(shù)據(jù)庫(kù)名稱* @param userName 用戶名* @param password 密碼* @return*/public static boolean restore(String restoreFilePath, String host, String userName, String password, String database)throws Exception {File restoreFile = new File(restoreFilePath);if (restoreFile.isDirectory()) {for (File file : restoreFile.listFiles()) {if (file.exists() && file.getPath().endsWith(".sql")) {restoreFilePath = file.getAbsolutePath();break;}}}StringBuilder stringBuilder = new StringBuilder();stringBuilder.append("mysql -h").append(host).append(" -u").append(userName).append(" -p").append(password);stringBuilder.append(" ").append(database).append(" < ").append(restoreFilePath);try {Process process = Runtime.getRuntime().exec(getCommand(stringBuilder.toString()));if (process.waitFor() == 0) {System.out.println("數(shù)據(jù)已從 " + restoreFilePath + " 導(dǎo)入到數(shù)據(jù)庫(kù)中");}} catch (IOException e) {e.printStackTrace();return false;}return true;}private static String[] getCommand(String command) {String os = System.getProperty("os.name"); String shell = "/bin/bash";String c = "-c";if(os.toLowerCase().startsWith("win")){ shell = "cmd";c = "/c";} String[] cmd = { shell, c, command };return cmd;}public static void main(String[] args) throws Exception {String host = "localhost";String userName = "root";String password = "123456";String database = "mango";System.out.println("開始備份");String backupFolderPath = "c:/dev/";String fileName = "mango.sql";backup(host, userName, password, backupFolderPath, fileName, database);System.out.println("備份成功");System.out.println("開始還原");String restoreFilePath = "c:/dev/mango.sql";restore(restoreFilePath, host, userName, password, database);System.out.println("還原成功");}}service層:
@Service public class MysqlBackupServiceImpl implements MysqlBackupService {@Overridepublic boolean backup(String host, String userName, String password, String backupFolderPath, String fileName,String database) throws Exception {return MySqlBackupRestoreUtils.backup(host, userName, password, backupFolderPath, fileName, database);}@Overridepublic boolean restore(String restoreFilePath, String host, String userName, String password, String database)throws Exception {return MySqlBackupRestoreUtils.restore(restoreFilePath, host, userName, password, database);}} @Component @ConfigurationProperties(prefix = "mango.backup.datasource") public class BackupDataSourceProperties {private String host;private String userName;private String password;private String database;public String getHost() {return host;}public void setHost(String host) {this.host = host;}public String getUserName() {return userName;}public void setUserName(String userName) {this.userName = userName;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public String getDatabase() {return database;}public void setDatabase(String database) {this.database = database;}}常量:
public interface BackupConstants {/** 備份目錄名稱 */public static final String BACKUP_FOLDER_NAME = "_my_backup";/** 備份目錄 */public static final String BACKUP_FOLDER = System.getProperty("user.home") + File.separator + BACKUP_FOLDER_NAME + File.separator;/** 還原目錄,默認(rèn)就是備份目錄 */public static final String RESTORE_FOLDER = BACKUP_FOLDER;/** 日期格式 */public static final String DATE_FORMAT = "yyyy-MM-dd_HHmmss";/** SQL拓展名 */public static final String SQL_EXT = ".sql";/** 默認(rèn)備份文件名 */public static final String BACKUP_FILE_NAME = "my" + SQL_EXT;/** 默認(rèn)備份還原目錄名稱 */public static final String DEFAULT_BACKUP_NAME = "backup";/** 默認(rèn)備份還原文件 */public static final String DEFAULT_RESTORE_FILE = BACKUP_FOLDER + DEFAULT_BACKUP_NAME + File.separator + BACKUP_FILE_NAME;}controller:
@RestController @RequestMapping("/backup") public class MySqlBackupController {@AutowiredMysqlBackupService mysqlBackupService;@AutowiredBackupDataSourceProperties properties;@GetMapping("/backup")public HttpResult backup() {String backupFodlerName = BackupConstants.DEFAULT_BACKUP_NAME + "_" + (new SimpleDateFormat(BackupConstants.DATE_FORMAT)).format(new Date());return backup(backupFodlerName);}private HttpResult backup(String backupFodlerName) {String host = properties.getHost();String userName = properties.getUserName();String password = properties.getPassword();String database = properties.getDatabase();String backupFolderPath = BackupConstants.BACKUP_FOLDER + backupFodlerName + File.separator;String fileName = BackupConstants.BACKUP_FILE_NAME;try {boolean success = mysqlBackupService.backup(host, userName, password, backupFolderPath, fileName, database);if(!success) {HttpResult.error("數(shù)據(jù)備份失敗");}} catch (Exception e) {return HttpResult.error(500, e.getMessage());}return HttpResult.ok();}@GetMapping("/restore")public HttpResult restore(@RequestParam String name) throws IOException {String host = properties.getHost();String userName = properties.getUserName();String password = properties.getPassword();String database = properties.getDatabase();String restoreFilePath = BackupConstants.RESTORE_FOLDER + name;try {mysqlBackupService.restore(restoreFilePath, host, userName, password, database);} catch (Exception e) {return HttpResult.error(500, e.getMessage());}return HttpResult.ok();}@GetMapping("/findRecords")public HttpResult findBackupRecords() {if(!new File(BackupConstants.DEFAULT_RESTORE_FILE).exists()) {// 初始默認(rèn)備份文件backup(BackupConstants.DEFAULT_BACKUP_NAME);}List<Map<String, String>> backupRecords = new ArrayList<>();File restoreFolderFile = new File(BackupConstants.RESTORE_FOLDER);if(restoreFolderFile.exists()) {for(File file:restoreFolderFile.listFiles()) {Map<String, String> backup = new HashMap<>();backup.put("name", file.getName());backup.put("title", file.getName());if(BackupConstants.DEFAULT_BACKUP_NAME.equalsIgnoreCase(file.getName())) {backup.put("title", "系統(tǒng)默認(rèn)備份");}backupRecords.add(backup);}}// 排序,默認(rèn)備份最前,然后按時(shí)間戳排序,新備份在前面backupRecords.sort((o1, o2) -> BackupConstants.DEFAULT_BACKUP_NAME.equalsIgnoreCase(o1.get("name")) ? -1: BackupConstants.DEFAULT_BACKUP_NAME.equalsIgnoreCase(o2.get("name")) ? 1 : o2.get("name").compareTo(o1.get("name")));return HttpResult.ok(backupRecords);}@GetMapping("/delete")public HttpResult deleteBackupRecord(@RequestParam String name) {if(BackupConstants.DEFAULT_BACKUP_NAME.equals(name)) { return HttpResult.error("系統(tǒng)默認(rèn)備份無(wú)法刪除!");}String restoreFilePath = BackupConstants.BACKUP_FOLDER + name;try {FileUtils.deleteFile(new File(restoreFilePath));} catch (Exception e) {return HttpResult.error(500, e.getMessage());}return HttpResult.ok();}}總結(jié)
以上是生活随笔為你收集整理的案例代码:sprimngboot备份数据库的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: springcloud、consul和S
- 下一篇: slf4j的jar包冲突:LoggerF