java服务 备份恢复mysql数据库

package com.kedacom.ics.utils;

import com.kedacom.ics.core.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;


/**
 * 数据库备份与还原
 * @author wangshuxuan
 * @date 2018/12/4 17:41
 */
public class DbOperate {

    private static Logger logger = LoggerFactory.getLogger(DbOperate.class);

    /**
     * 备份数据库db
     * @param root
     * @param pwd
     * @param dbName
     * @param backPath
     * @param backName
     */
    public static void dbBackUp(String root,String pwd,String hostIp,String dbName,String backPath,String backName){

        try {
            String pathSql = backPath+backName;
            File fileSql = new File(pathSql);
            //创建备份sql文件
            if (!fileSql.exists()){
                fileSql.createNewFile();
            }
            //mysqldump -hlocalhost -uroot -p123456 db > /home/back.sql
            StringBuffer sb = new StringBuffer();
            sb.append("mysqldump");
            sb.append(" -h"+hostIp);
            sb.append(" -u"+root);
            sb.append(" -p"+pwd);
            sb.append(" "+dbName);
            sb.append(" --skip-lock-tables"+" >");
            sb.append(pathSql);
            logger.info("cmd命令为:"+sb.toString());
            Runtime runtime = Runtime.getRuntime();
            logger.info("开始备份:"+dbName);
            //获取当前操作系统
            String systemName = System.getProperty("os.name").toLowerCase();
            if (systemName.startsWith("win")) {
                Process process = runtime.exec("cmd /c D:\\mysql-5.6.21-win32\\bin\\"+sb.toString());
                process.waitFor();   //阻塞等待执行完
            }else {
                Process process = runtime.exec("cmd /c"+sb.toString());
                process.waitFor();
            }
            logger.info("备份成功!");
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("备份失败!");
        }
    }

    /**
     * 恢复数据库
     * @param root
     * @param pwd
     * @param dbName
     * @param file
     */
    public static void dbRestore(String root, String pwd, String hostIp, String dbName, MultipartFile file){

//        File file = new File(filePath);
//        //如果不存在
//        if (!file.exists()) {
//            throw new BusinessException("文件不存在,请先备份!");
//        }
        StringBuilder sb = new StringBuilder();
        sb.append("mysql");
        sb.append(" -h"+hostIp);
        sb.append(" -u"+root);
        sb.append(" -p"+pwd);
        sb.append(" "+dbName);
        logger.info("cmd命令为:"+sb.toString());
        Runtime runtime = Runtime.getRuntime();
        logger.info("开始还原数据");
        Process process = null;
        try {
            String systemName = System.getProperty("os.name").toLowerCase();
            if (systemName.startsWith("win")) {
                process = runtime.exec("cmd /c D:\\mysql-5.6.21-win32\\bin\\"+sb.toString());
            }else {
                process = runtime.exec("cmd /c"+sb.toString());
            }
            OutputStream outputStream = process.getOutputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(file.getInputStream(),"utf8"));
            String str = null;
            StringBuffer stringBuffer = new StringBuffer();
            while ((str = br.readLine()) != null) {
                stringBuffer.append(str + "\r\n");
            }
            str = stringBuffer.toString();
            //logger.info(str);
            OutputStreamWriter writer = new OutputStreamWriter(outputStream,
                    "utf-8");
            writer.write(str);
            writer.flush();
            outputStream.close();
            br.close();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        logger.info("还原成功!");
    }
}

在mysql5.6以上 >db.sql好像不太行,不知道为什么,所以改为自己创建文件,以流的方式写入文件,5,6以上还有gtid的新特性。

**
     * 备份数据库db
     * @param root
     * @param pwd
     * @param dbName
     * @param backPath
     * @param backName
     */
    public static void dbBackUp(String root,String pwd,String hostIp,String dbName,String backPath,String backName){

        PrintWriter printWriter = null;
        BufferedReader bufferedReader = null;
        try {
            String pathSql = backPath+backName;
            File fileSql = new File(pathSql);
            //创建备份sql文件
            if (!fileSql.exists()){
                fileSql.createNewFile();
            }
            //mysqldump -hlocalhost -uroot -p123456 db > /home/back.sql
            StringBuffer sb = new StringBuffer();
            sb.append("mysqldump");
            sb.append(" -h"+hostIp);
            sb.append(" -u"+root);
            sb.append(" -p"+pwd);
            sb.append(" --set-charset=UTF8");
            sb.append(" "+dbName);
            sb.append(" --set-gtid-purged=OFF");
            //sb.append(pathSql);
            logger.info("cmd命令为:"+sb.toString());
            Runtime runtime = Runtime.getRuntime();
            logger.info("开始备份:"+dbName);
            //获取当前操作系统
            String systemName = System.getProperty("os.name").toLowerCase();
            if (systemName.startsWith("win")) {
                logger.info("cmd命令为:cmd /c D:\\mysql-5.6.21-win32\\bin\\" + sb.toString());
                printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(pathSql), "utf8"));
                Process process = runtime.exec("cmd /c D:\\mysql-5.6.21-win32\\bin\\"+sb.toString());
                InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream(), "utf8");
                bufferedReader = new BufferedReader(inputStreamReader);
                String line;
                while((line = bufferedReader.readLine())!= null){
                    printWriter.println(line);
                }
                printWriter.flush();
                //阻塞等待完成
                process.waitFor();
            }else {
                logger.info(sb.toString());
                printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(pathSql), "utf8"));
                Process process = runtime.exec(sb.toString());
                InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream(), "utf8");
                bufferedReader = new BufferedReader(inputStreamReader);
                String line;
                while((line = bufferedReader.readLine())!= null){
                    printWriter.println(line);
                }
                printWriter.flush();
                //阻塞等待完成
                process.waitFor();
            }
            logger.info("备份成功!");
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("备份失败!");
        }finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
                if (printWriter != null) {
                    printWriter.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                throw new BusinessException("备份失败!");
            }
        }
    }

猜你喜欢

转载自blog.csdn.net/qq_38999810/article/details/84878903