如何從Springboot排程中備份mariadb資料庫?

本文章以CentOS7為例

首先從application.properties新增三個參數

config.db_backup=/usr/local/soft/tomcat/
#備份路徑
config.db_backup_exe=/usr/bin
#mysqldump執行檔路徑
config.db_backup_remote=172.18.0.2
#資料庫位置,遠端填上主機ip,本地則留空

排程程式範例如下
				
					import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.concurrent.TimeUnit;

import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteWatchdog;
import org.apache.commons.exec.PumpStreamHandler;
import org.apache.logging.log4j.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.zaxxer.hikari.HikariDataSource;

@Component
public class DataBaseBackUpTasks {
    Logger logger = LoggerFactory.getLogger(DataBaseBackUpTasks.class);
	
    @Autowired
    private HikariDataSource hikariDataSource;
	
    @Value("${config.db_backup}")
    private String db_backup;
	
    @Value("${config.db_backup_exe}")
    private String db_backup_exe;
	
    @Value("${config.db_backup_remote}")
    private String db_backup_remote;

    @Scheduled(cron="0 0 1 * * ?")
    //排程凌晨1點開始備份
    public void backup(){
		File db_backup_path = new File(db_backup);
		if(!db_backup_path.exists()){
			db_backup_path.mkdirs();
		}
		Path sqlFile = Paths.get(db_backup+File.separator+"db.sql");
		
		String database = null;

		// 執行SQL取得檔案資料庫名稱
		try (Connection connection = hikariDataSource.getConnection()) {
			try (ResultSet resultSet = connection.createStatement().executeQuery("SELECT DATABASE();")) {
				if (resultSet.next()) {
					database = resultSet.getString(1);
				}
			}
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
		
		// 異常輸出
		ByteArrayOutputStream stdErr = new ByteArrayOutputStream();
		
		try {
			OutputStream stdOut = new BufferedOutputStream(Files.newOutputStream(sqlFile, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING));
			
			// 監控執行超過時間1小時
			ExecuteWatchdog watchdog = new ExecuteWatchdog(TimeUnit.HOURS.toMillis(1));
			
			DefaultExecutor defaultExecutor = new DefaultExecutor();
			defaultExecutor.setWorkingDirectory(null);
			defaultExecutor.setWatchdog(watchdog);
			defaultExecutor.setStreamHandler(new PumpStreamHandler(stdOut, stdErr));		

			// 執行命令
			CommandLine commandLine = new CommandLine(db_backup_exe+File.separator+"mysqldump");
			commandLine.addArgument("-u" + hikariDataSource.getUsername());
			if(!Strings.isEmpty(hikariDataSource.getPassword())){
				commandLine.addArgument("-p" + hikariDataSource.getPassword());
			}
			if(!Strings.isEmpty(db_backup_remote)){
				commandLine.addArgument("-h" + db_backup_remote); 
			}
			commandLine.addArgument(database);

			logger.info("輸出SQL資料...");
			
			int exitCode = defaultExecutor.execute(commandLine);
			
			if(defaultExecutor.isFailure(exitCode) && watchdog.killedProcess()) {
				logger.error("備份超時");
			}
			
			logger.info("SQL資料導出成功: exitCode={}, sqlFile={}", exitCode, sqlFile.toString());

		} catch (Exception e) {
			logger.error("SQL資料導出異常: {}", e.getMessage());
			logger.error("std err: {}{}", System.lineSeparator(), stdErr.toString());
		}
    }
}
				
			

Leave a Comment

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *