window环境:
//mysqldump命令路径 private String mysqldumpPath; //备份文件存放路径 String backupPath; /** * mysqldump -u用户名 -密码 数据库名 > 文件全路径 */ String cmd = "cmd /c mysqldump -uroot -pmysql cloud_user > " + backupPath + "backup_cloud_user.sql"; Runtime.getRuntime().exec(cmd);Linux环境: 注意:
脚本文件需要赋予权限:chmod 777 mysqlBackup.sh如果是docker部署,基础镜像不能用alpine版本,可能会报文件找不到错误mysqlBackup.sh(备份数据库脚本)
#!/bin/bash . /etc/profile echo you passed parameters host=$1 DBUser=$2 DBPass=$3 DBName=$4 BackupPath=$5 /usr/bin/mysqldump -h$host -u$DBUser -p$DBPass --opt $DBName --result-file=$BackupPath String[] cmd = new String[]{"/bin/sh", "-c", "mysqlBackup.sh ip地址 mysql用户名 mysql密码 数据库名 备份文件全路径"}; ProcessBuilder builder = new ProcessBuilder(cmd); try { Process process = builder.start(); BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream())); BufferedReader brError = new BufferedReader(new InputStreamReader(process.getErrorStream())); String line; while ((line = br.readLine()) != null) { log.info("readLine:{}", line); } while ((line = brError.readLine()) != null) { log.info("errorLine:{}", line); } br.close(); sign = process.waitFor(); } catch (Exception e) { log.info("备份命令执行失败"); } finally { if (sign == 0) { log.info("备份命令执行成功"); } else { log.info("备份命令执行失败"); } }