萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 資料庫 >> 資料庫綜合

Java 實現 MySQL 資料庫匯入匯出工具類:Runtime.exec 最佳實踐與坑點避雷

核心思路:進程管道與串流控制

Java 呼叫 mysqldump (匯出) 與 mysql 客戶端 (匯入) 的本質是子進程管道通訊。關鍵點:

  1. 匯出:單進程,標準輸出重導向至檔案 (或 Java 讀取 InputStream)
  2. 匯入:互動式進程,需依序寫入:登入 → 切庫 → 執行 source 指令

生產級工具類完整實現

package com.example.db.util;

import lombok.extern.slf4j.Slf4j;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

@Slf4j
public class MySqlImportExportUtil {

    private final String host;
    private final int port;
    private final String username;
    private final String password;
    private final String mysqldumpPath;
    private final String mysqlPath;

    public MySqlImportExportUtil(Properties props) {
        this.host = props.getProperty("jdbc.host", "localhost");
        this.port = Integer.parseInt(props.getProperty("jdbc.port", "3306"));
        this.username = props.getProperty("jdbc.username");
        this.password = props.getProperty("jdbc.password");
        this.mysqldumpPath = props.getProperty("jdbc.mysqldumpPath", "mysqldump");
        this.mysqlPath = props.getProperty("jdbc.mysqlPath", "mysql");
    }

    /**
     * 匯出資料庫到 SQL 檔案 (支援壓縮)
     */
    public void exportDatabase(String databaseName, File outputFile, boolean compress) 
            throws IOException, InterruptedException {
        
        StringBuilder cmd = new StringBuilder();
        cmd.append(mysqldumpPath)
           .append(" -h").append(host)
           .append(" -P").append(port)
           .append(" -u").append(username)
           .append(" -p").append(password)  // 注意:-p 後無空格直接接密碼
           .append(" --single-transaction")  // InnoDB 熱備不鎖表
           .append(" --routines --triggers --events")
           .append(" --master-data=2")       // 記錄 Binlog 位置 (PITR)
           .append(" --hex-blob")            // 二進位欄位十六進位
           .append(" --quick")               // 大表逐行串流,不緩衝
           .append(" --default-character-set=utf8mb4")
           .append(" ").append(databaseName);

        if (compress) {
            cmd.append(" | gzip > ").append(outputFile.getAbsolutePath());
            executeShellCommand(cmd.toString());
        } else {
            // 使用 -r 參數指定輸出檔案 (跨平台相容,避免 Shell 重導向問題)
            cmd.append(" -r ").append(outputFile.getAbsolutePath());
            executeCommand(cmd.toString());
        }
        
        log.info("Export completed: {} ({} bytes)", outputFile.getAbsolutePath(), outputFile.length());
    }

    /**
     * 從 SQL 檔案匯入資料庫 (支援 .gz 壓縮檔)
     */
    public void importDatabase(String databaseName, File inputFile) 
            throws IOException, InterruptedException {
        
        // 建立目標資料庫 (若不存在)
        executeCommand(String.format("%s -h%s -P%d -u%s -p%s -e \"CREATE DATABASE IF NOT EXISTS `%s` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;\"",
                mysqlPath, host, port, username, password, databaseName));

        // 匯入邏輯:處理壓縮與非壓縮
        ProcessBuilder pb;
        if (inputFile.getName().endsWith(".gz")) {
            // zcat | mysql 管道串流 (Linux/Mac)
            // Windows 需用 gzip -dc 或 Java 解壓後管道
            pb = new ProcessBuilder("bash", "-c", 
                String.format("zcat %s | %s -h%s -P%d -u%s -p%s %s",
                    inputFile.getAbsolutePath(), mysqlPath, host, port, username, password, databaseName));
        } else {
            // 直接重導向輸入 (跨平台)
            pb = new ProcessBuilder(mysqlPath, 
                "-h"+host, "-P"+String.valueOf(port), 
                "-u"+username, "-p"+password, 
                databaseName);
            pb.redirectInput(inputFile);
        }

        pb.redirectErrorStream(true);
        Process process = pb.start();
        
        // 非同步讀取輸出避免緩衝區滿阻塞
        new Thread(() -> {
            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    log.debug("[IMPORT] {}", line);
                }
            } catch (IOException e) {
                log.error("Import output read error", e);
            }
        }).start();

        boolean finished = process.waitFor(30, TimeUnit.MINUTES);
        if (!finished) {
            process.destroyForcibly();
            throw new RuntimeException("Import timeout after 30 minutes");
        }
        
        if (process.exitValue() != 0) {
            throw new RuntimeException("Import failed with exit code: " + process.exitValue());
        }
        
        log.info("Import completed from: {}", inputFile.getAbsolutePath());
    }

    /**
     * 執行單一命令 (非 Shell 管道)
     */
    private void executeCommand(String command) throws IOException, InterruptedException {
        ProcessBuilder pb = new ProcessBuilder(command.split(" "));
        pb.redirectErrorStream(true);
        Process process = pb.start();
        logProcessOutput(process);
        int exitCode = process.waitFor();
        if (exitCode != 0) throw new RuntimeException("Command failed (exit " + exitCode + "): " + command);
    }

    /**
     * 執行 Shell 命令 (支援管道、重導向)
     */
    private void executeShellCommand(String command) throws IOException, InterruptedException {
        ProcessBuilder pb = new ProcessBuilder("bash", "-c", command);
        pb.redirectErrorStream(true);
        Process process = pb.start();
        logProcessOutput(process);
        int exitCode = process.waitFor();
        if (exitCode != 0) throw new RuntimeException("Shell command failed (exit " + exitCode + "): " + command);
    }

    private void logProcessOutput(Process process) {
        new Thread(() -> {
            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    log.debug("[CMD] {}", line);
                }
            } catch (IOException ignored) {}
        }).start();
    }
}

配置檔範例 (jdbc.properties)

jdbc.host=127.0.0.1
jdbc.port=3306
jdbc.username=backup_user
jdbc.password=Str0ngP@ssw0rd
jdbc.mysqldumpPath=/usr/bin/mysqldump
jdbc.mysqlPath=/usr/bin/mysql

Spring Boot 整合範例

@Component
public class DatabaseBackupService {

    @Autowired MySqlImportExportUtil util;
    @Value("${backup.dir:/data/backups}") String backupDir;
    @Value("${backup.retention-days:7}") int retentionDays;

    @Scheduled(cron = "0 0 4 * * ?") // 每日 04:00
    public void dailyBackup() {
        String dbName = "production_db";
        File backupFile = new File(backupDir, "mysql-" + LocalDate.now() + ".sql.gz");
        try {
            util.exportDatabase(dbName, backupFile, true);
            cleanupOldBackups();
        } catch (Exception e) {
            log.error("Daily backup failed", e);
            alertService.sendAlert("MySQL 備份失敗: " + e.getMessage());
        }
    }

    private void cleanupOldBackups() {
        File dir = new File(backupDir);
        File[] files = dir.listFiles((d, name) -> name.startsWith("mysql-") && name.endsWith(".sql.gz"));
        if (files != null) {
            for (File f : files) {
                if (Duration.between(f.lastModified().toInstant(), Instant.now()).toDays() > retentionDays) {
                    f.delete();
                    log.info("Deleted old backup: {}", f.getName());
                }
            }
        }
    }
}

關鍵坑點與避雷指南

坑點 現象 解決方案
密碼特殊字元 Shell 解析錯誤 (含 $, !, %, *, 空格等) 使用 --password= 等號語法,或透過 --defaults-extra-file 指定 cnf 檔
Windows 路徑空格 命令解析中斷 路徑加雙引號,或使用 ProcessBuilder 陣列模式避免 Shell 解析
大檔案匯入阻塞 進程掛起、無回應 非同步讀取 stdout/stderr (如上方 logProcessOutput),避免管道緩衝區滿
字元集亂碼 中文變 ??? 或亂碼 統一指定 --default-character-set=utf8mb4,資料庫/表/連線皆 utf8mb4
權限不足 Access denied / SELECT INTO OUTFILE 權限 備份帳號需 SELECT, LOCK TABLES, SHOW VIEW, EVENT, TRIGGER, PROCESS 權限
版本不匹配 mysqldump 版本 > Server 版本報錯 客戶端工具版本 ≤ Server 版本,或加 --column-statistics=0 (8.0+)

進階替代方案:純 Java 實現 (零依賴外部命令)

  • 匯出: 使用 SELECT ... INTO OUTFILE (需 FILE 權限) 或 JDBC 讀取逐行生成 INSERT
  • 匯入: JDBC 批次執行 PreparedStatement.addBatch(),配合 rewriteBatchedStatements=true 連線參數
  • 庫: mysqldump-java - 純 Java 實現 mysqldump 協議

掌握 Runtime.exec/ProcessBuilder 的管道串流控制、字元編碼、錯誤處理與超時機制,是構建穩健資料庫運維工具的關鍵。生產環境建議結合雲端快照、PITR、Binlog 歸檔構建多層備份體系。

copyright © 萬盛學電腦網 all rights reserved