在以前开发中我不幸把数据库给删掉了,一气之下就打了一个数据库备份的工具类。
配置如下:
mysqlDataBase:
name: fandeng #备份的数据库名
url: E:\www\fandengDB
ip: 192.168.0.115
工具类代码如下:
package com.meeno.framework.timingTask;
import com.meeno.framework.util.DateUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.IOException;
import java.util.Date;
/**
* @program: fandeng
* @description: 数据库定时任务备份
* @author: Wzq
* @create: 2019-08-05 16:23
*/
@Configuration
@Component
public class DateBaseSqlBackupTimingTask {
//备份的数据库名
@Value("${mysqlDataBase.name}")
private String dbName;
//用户名
@Value("${spring.datasource.username}")
private String username;
//密码
@Value("${spring.datasource.password}")
private String password;
//备份数据库文件地址
@Value("${mysqlDataBase.url}")
private String filePath;
//ip地址
@Value("${mysqlDataBase.ip}")
private String ip;
//3.添加定时任务 每天晚上2点
@Scheduled(cron = "0 0 2 * * ?")
//或直接指定时间间隔,例如:5秒
// @Scheduled(fixedRate=5000)
//十分钟
//@Scheduled(cron = "0 */10 * * * ?")
public void configureTasks() {
Date now = new Date();
System.out.println("执行定时任务》》》"+now);
// String filePath="D:\\数据库文件\\";
// String dbName="springbootdb";//备份的数据库名
// String username="root";//用户名
// String password="mysql";//密码
File uploadDir = new File(filePath);
if (!uploadDir.exists())
uploadDir.mkdirs();
String dateStr = filePath + File.separator + DateUtil.getDateDetailStr(now) + now.getTime()+".sql";
System.out.println("备份文件路径》》》"+dateStr);
File tempFile = new File(dateStr);
if (!tempFile.exists()) {
try {
tempFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
String cmd = "mysqldump -h"+ip+" -u"+ username +" -p"+password + " " + dbName + " -r "
+ dateStr;
try {
// synchronized (Runtime.getRuntime()) {
//
// }
System.out.println(System.currentTimeMillis() + ": 开始执行数据库备份");
Process process = Runtime.getRuntime().exec(cmd);
System.out.println(System.currentTimeMillis() + ":备份数据库成功!!!");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
注意:
windows上mysql要配置全局变量,配置完成后要重启才能生效。
技术支持:高岳峰,闫宇峰,施凯雷,杨珂
他的个人博客地址:http://120.78.93.197/
这是我的公众号 有最新的it咨询,和个人工作的记录:
这是我的个人微信遇到问题欢迎,提问:
最后加上高质量的淘宝店:如有质量问题随时滴滴我,童叟无欺!
【童装园服定制店铺】https://m.tb.cn/h.ef2J8CD?sm=6e0f74 点击链接,再选择浏览器咑閞;或復·制这段描述¥zfwjY4JVngW¥后到淘♂寳♀