Java将数据库文件备份到服务器本地(开发小记)

导入okhttp3依赖

<dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>3.6.0</version>
</dependency>

在springboot项目的工具包中(我的是utils)创建一个名为BackupTask的Class

让springboot启动时能扫描到,springboot简化了设置,会扫描主程序类下的所有子包

package com.fcwr;

import com.alibaba.fastjson.JSONObject;
import okhttp3.*;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;


@Component
public class BackupTask {

    //    @Value("${druid.username}")
    private String userName = "";
    //    @Value("${druid.password}")
    private String password = "";

    //    private static final String WEB_URL = "";
    private DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmm");//我测试用的分钟,正式使用可以把后面的mm去掉

    private static final String BACKUP_PATH = "/home/tomcat/backup";
    private static final int EXPIRED_MONTH = -3;

    @Scheduled(cron = "0 0/5 * * * ? *")//测试时候的Cron表达式
    public void task() {

        String gzFileName = BACKUP_PATH + dateFormat.format(new Date()) + ".tar.gz";
        File file = new File(gzFileName);

        if (backup(userName, password, gzFileName)) {
            System.out.println(dateFormat.format(new Date()) + "===成功备份数据库===");
            deleteExpiredFile();
//            try {
//                String body = upload(WEB_URL, gzFileName);
                //JSONObject jsonObject = JSONObject.parseObject(body);
                //if (file.exists()) file.delete();
              
//            } catch (Exception e) {
//                e.printStackTrace();
  //          }
        } else {
            System.out.println(dateFormat.format(new Date()) + "===备份数据库失败===");
        }

    }

    private void deleteExpiredFile() {
        File backupFile = new File(BACKUP_PATH);
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, EXPIRED_MONTH);
        long expiredTime = calendar.getTimeInMillis();
        File[] fileList = backupFile.listFiles(new FileFilter() {
            @Override
            public boolean accept(File pathname) {

                if (pathname.getName().endsWith(".tar.gz")
                        && pathname.lastModified() < expiredTime) {
                    return true;
                } else {
                    return false;
                }
            }
        });
        for (File file : fileList) {
            file.delete();
        }
    }

//   上传备份看情况使用
//    private String upload(String url, String filePath) throws Exception {
//        OkHttpClient client = new OkHttpClient();
//        File file = new File(filePath);
//        RequestBody requestBody = new MultipartBody.Builder()
//                .setType(MultipartBody.FORM)
//                .addFormDataPart("file", file.getName(),
//                        RequestBody.create(MediaType.parse("multipart/form-data"), new File(filePath)))
//                .build();
//
//        Request request = new Request.Builder()
//                .url(url)
//                .post(requestBody)
//                .build();
//
//        Response response = client.newCall(request).execute();
//        if (!response.isSuccessful()) return "{\"code\":1}";
//        return response.body().string();
//    }

    private boolean backup(String userName, String password, String gzFileName) {
        String bakFileName = BACKUP_PATH + "test.sql";
        if (exportDatabase(userName, password, bakFileName)) {
            try {
                Process process = Runtime.getRuntime().exec("tar -cvzf " + gzFileName + " " + bakFileName);
                if (process.waitFor() == 0) {
                    File file = new File(bakFileName);
                    if (file.exists()) file.delete();
                   
                    return true;
                }
            } catch (IOException | InterruptedException e) {
                e.printStackTrace();
            }
            return false;
        } else {
            return false;
        }

    }


    private boolean exportDatabase(String userName, String password, String bakFileName) {

        PrintWriter printWriter = null;
        BufferedReader bufferedReader = null;
        try {
            printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(bakFileName), "utf8"));

            Process process = Runtime.getRuntime().exec(" mysqldump -h 127.0.0.1" + " -u" + userName + " -p" + password + " --set-charset=UTF8 test");
            InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream(), "utf8");
            bufferedReader = new BufferedReader(inputStreamReader);
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                printWriter.println(line);
            }
            printWriter.flush();
            if (process.waitFor() == 0) {//0 表示线程正常终止。

                return true;
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
                if (printWriter != null) {
                    printWriter.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }
}

启动类需要添加

@EnableScheduling

版权声明:本文为weixin_42078172原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。