spring boot 定时备份数据库

时间:2023-12-29 18:07:32

第一步 :添加mysqldump.exe 进环境变量

spring boot 定时备份数据库

第二步  新建一个spring boot 项目,连接数据库

spring.datasource.url=jdbc:mysql://localhost:3308/springbootdb?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true
spring.datasource.username=root
spring.datasource.password=mysql
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

第三步  添加相关需要的jar

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- quartz -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>

第四步 创建定时任务

    /**
* 执行定时任务
*/
@Override
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
// TODO Auto-generated method stub
System.out.println("执行定时任务》》》"+new Date());
String filePath="D:\\数据库文件\\";
String dbName="springbootdb";//备份的数据库名
String username="root";//用户名
String password="mysql";//密码
File uploadDir = new File(filePath);
if (!uploadDir.exists())
uploadDir.mkdirs(); String cmd = "mysqldump -u"+ username +" -p "+password + dbName + " -r "
+ filePath + "/" + dbName+new java.util.Date().getTime()+ ".sql";
try {
Process process = Runtime.getRuntime().exec(cmd);
System.out.println("备份数据库成功!!!");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace(); } }

第五步  配置quartz,设置每10秒执行一次定时任务

@Configuration
public class QuartzConfig {
@Bean
public JobDetail teatQuartzDetail(){
return JobBuilder.newJob(TestQuartz.class).withIdentity("testQuartz").storeDurably().build();
} @Bean
public Trigger testQuartzTrigger(){
SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule()
.withIntervalInSeconds(10) //设置时间周期单位秒
.repeatForever();
return TriggerBuilder.newTrigger().forJob(teatQuartzDetail())
.withIdentity("testQuartz")
.withSchedule(scheduleBuilder)
.build();
} }

第六步  运行项目

spring boot 定时备份数据库

备份成功!!!!!!!!!!!!!!!!!!!!

spring boot 定时备份数据库

github项目地址    copyDatabase