前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >mySql每天自动备份数据库

mySql每天自动备份数据库

作者头像
用户5927264
发布2022-06-26 09:15:35
2.5K0
发布2022-06-26 09:15:35
举报
文章被收录于专栏:OSChinaOSChina
  1. 工具类
代码语言:javascript
复制
package cn.stylefeng.guns.modular.task;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * @author shiye
 * @create 2022-06-22 16:27
 */
public class DbUtil {

    private static final Log logger = LogFactory.getLog(DbUtil.class);

    public static void backup(File file, String user, String password, String db, String ip) throws IOException {
        InputStream inputStream = null;
        BufferedReader bufferedReader = null;
        OutputStreamWriter outputStreamWriter = null;
        try {
            Runtime rt = Runtime.getRuntime();
            /**
             * 这是在windows下使用得数据备份命令:C:/Program Files/MySQL/MySQL Server 5.7/bin/mysqldump
             * 在liunx下需要尝试:mysqldump
             */
            String command = "C:/Program Files/MySQL/MySQL Server 5.7/bin/mysqldump -u" + user + " -p" + password + " -h " + ip + " " + " --databases " + db;
            logger.info("备份数据得命令:" + command);

            Process child = rt.exec(command);
            inputStream = child.getInputStream();
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            outputStreamWriter = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8);
            String str;

            //flag 用来标识是否有数据备份,默认没有false
            boolean flag = false;
            while ((str = bufferedReader.readLine()) != null) {
                outputStreamWriter.write(str + "\r\n");
                flag = true;
            }
            if (!flag) {
                throw new IOException("没有数据需要备份...");
            }
            outputStreamWriter.flush();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("导出excel报错:", e.getCause());
            throw e;
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
            if (bufferedReader != null) {
                bufferedReader.close();
            }
            if (outputStreamWriter != null) {
                outputStreamWriter.close();
            }
        }
    }

    public static void load(File file, String user, String password, String db) {
        try {
            Runtime rt = Runtime.getRuntime();
            String command = "mysql -u" + user + " -p" + password + " --default-character-set=utf8 " + db;
            Process child = rt.exec(command);
            OutputStream outputStream = child.getOutputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8));
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8);
            String str;
            while ((str = bufferedReader.readLine()) != null) {
                outputStreamWriter.write(str + "\r\n");
            }
            outputStreamWriter.flush();
            outputStream.close();
            bufferedReader.close();
            outputStreamWriter.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 2. 每天2点定时执行得定时任务

代码语言:javascript
复制
package cn.stylefeng.guns.modular.task;

import cn.stylefeng.guns.modular.system.model.Notice;
import cn.stylefeng.guns.modular.system.service.INoticeService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * @author shiye
 * @create 2022-06-22 16:26
 */
@Component
public class DbJob {
    private final Log logger = LogFactory.getLog(DbJob.class);

    // Environment  environment 是用于获取spring配置文件值的接口
    @Autowired
    private Environment environment;

    //数据备份异常得时候 写入通知表进行页面通知
    @Autowired
    private INoticeService noticeService;

    /*
     * 定时时间是每天凌晨2点。
     */
    @Scheduled(cron = "0 0 2 * * ?")
    public void backup() throws IOException {
        logger.info("系统开启定时任务数据库备份");
        try {
            // 数据库用户名
            String user = environment.getProperty("spring.datasource.username");
            // 数据库密码
            String password = environment.getProperty("spring.datasource.password");
            // 数据库地址
            String url = environment.getProperty("spring.datasource.url");

            if (StringUtils.isEmpty(url)) {
                logger.error("没有数据需要导入 推出....");
                throw new IOException("没有查询到需要备份得url");
            }

            // 动态截取数据库url中的数据库名称
            int index1 = url.indexOf("3306/");
            int index2 = url.indexOf("?");
            String db = url.substring(index1 + 5, index2);

            int index3 = url.indexOf("jdbc:mysql://");
            int index4 = url.indexOf(":3306");
            String ip = url.substring(index3 + 13, index4);

            // 当前时间 年月日格式
            LocalDate localDate = LocalDate.now();
            // 备份文件名称
            String fileName = localDate.toString() + ".sql";
            // 输出
            File file = new File("backup", fileName);
            file.getParentFile().mkdirs();
            file.createNewFile();

            // 备份今天数据库
            DbUtil.backup(file, user, password, db, ip);
            // 删除15天前数据库备份文件
            LocalDate before = localDate.minusDays(15);
            String fileBeforeName = before.toString() + ".sql";
            File fileBefore = new File("backup", fileBeforeName);
            if (fileBefore.exists()) {
                logger.info("历史数据直接删除掉 :" + fileBeforeName);
                fileBefore.delete();
            }
        } catch (Exception e) {
            logger.error("备份数据库异常", e);
            Notice notice = new Notice();
            notice.setTitle("数据备份异常通知");
            notice.setCreatetime(new Date());
            notice.setType(1);
            notice.setContent("数据库在备份中出现错误,请联系管理员进行处理。数据备份时间:" + LocalDateTime.now());
            notice.setCreater(1);
            noticeService.insert(notice);
        }
        logger.info("系统结束定时任务数据库备份");
    }

}

3. 在启动类上增加注解

代码语言:javascript
复制
@EnableScheduling
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-06-24,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
云数据库 MySQL
腾讯云数据库 MySQL(TencentDB for MySQL)为用户提供安全可靠,性能卓越、易于维护的企业级云数据库服务。其具备6大企业级特性,包括企业级定制内核、企业级高可用、企业级高可靠、企业级安全、企业级扩展以及企业级智能运维。通过使用腾讯云数据库 MySQL,可实现分钟级别的数据库部署、弹性扩展以及全自动化的运维管理,不仅经济实惠,而且稳定可靠,易于运维。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档