Java实现msyql备份和恢复

目标

1.通过java实现mysql数据库的 备份和恢复,实现定时备份目标

2.物理机和docker环境都可以使用

步骤

1.编写shell脚本. 

脚本内容包括. 1)mysql客户端安装.2)mysql备份.3)mysql恢复

2.在程序中调用脚本

3.脚本放到项目资源目录,在项目运行时使用脚本.

代码

1.shell脚本

参数1: 1是备份 .2 是恢复

#!/bin/bash
isbackup=$1
host=$2
port=$3
user=$4
passwd=$5
dbname=$6
sqlpath=$7

#安装mysql客户端 跟随docker基础镜像
apt-get update
apt-get install -y default-mysql-client

#echo backup $isbackup
if [ $isbackup -eq 1 ]
then
        #备份echo mysqldump --host $host --port $port -u $user -p$passwd $dbname > $sqlpath
            mysqldump --default-character-set=utf8mb4 --host ${host} --port ${port} -u ${user} -p${passwd} ${dbname} > ${sqlpath}
elif [ $isbackup -eq 0 ]
then
    #恢复
    mysql --default-character-set=utf8mb4 --host ${host} --port ${port} -u ${user} -p${passwd} ${dbname} < ${sqlpath}
else
    echo isbackup error need 0 or 1
fi

2.java调用代码

ProcessBuilder processBuilder = new ProcessBuilder("sh","backup.sh",
                "1",
                "192.168.1.3",
                "3308",
                "root",
                "123456",
                "test",
                "/home/backup/dump.sql"
        );
        processBuilder.directory(new File("/backup"));
        Process process = processBuilder.start();
        int code = process.waitFor();
        if (code == 0) {
            System.out.println("备份数据成功");
        }else {
            System.out.println("备份失败,error code : "+ code);
        }

3.运行时创建脚本

private boolean isWindows() {
        // 检查是否为Windows环境
        String osName = System.getProperty("os.name").toLowerCase();
        boolean windows = osName.contains("windows");
        if (!windows) {
            File file = new File("/backup" + File.separator + "backup.sh");
            if (!file.exists()) {
                try (InputStream is = this.getClass().getClassLoader().getResourceAsStream("backup.sh");
                        FileOutputStream os = new FileOutputStream(file);) {
                    byte[] buffer = new byte[1024];
                    int length;
                    while ((length = is.read(buffer)) != -1) {
                        os.write(buffer, 0, length);
                    }
                    os.flush();
                } catch (Exception e) {
                    log.error("创建backup.sh异常");
                }
            }
        
try {
Files.write(scriptPath, content.getBytes(), StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING);

List<String> cmd = new ArrayList<>();
cmd.add("sed");
cmd.add("-i");
cmd.add("-e");
cmd.add( "s/\\r$//");
cmd.add("backup.sh");
ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.command(cmd);
processBuilder.directory(new File("/backup"));
Process process = processBuilder.start();
int code = process.waitFor();
System.out.println(code);
} catch (Exception e) {
e.printStackTrace();
}
} return windows; }

 

posted @ 2024-04-15 16:43  若星汉浮云  Views(240)  Comments(0Edit  收藏  举报