1.添加依赖
一个是SpringBatch依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-batch</artifactId>
</dependency>
一个是mysql依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
2.添加配置文件
# web visit port
server:
port: 8888
# mysql application
#url的格式:jdbc:驱动名://host:port/database?条件 useSSL是是否使用加密连接来访问
#schema:指的是模式 在这里指的是当你启动项目的时候 会根据指定的sql创建或更新模式
#schema:模式,在关系型数据库中,用于描述数据库中对象的逻辑结构和规范的集合,定义了表、视图、索引、存储过程、触发器等数据库对象的组织方式和相关属性。
spring:
datasource:
url: jdbc:mysql://localhost:3306/SpringBatch?useSSL=false&serverTimezone=Asia/Shanghai
username: root
password: root
hikari:
schema: classpath:/org/springframework/batch/core/schemal-mysql.sql
driver-class-name: com.mysql.cj.jdbc.Driver
batch:
jdbc:
initialize-schema: always
3.编写启动类
package com.pjk.springBatch.demo2;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@EnableBatchProcessing
@SpringBootApplication
public class SpringBatchMysqlDemo {
public static void main(String[] args) {
SpringApplication.run(SpringBatchMysqlDemo.class, args);
}
@Autowired
private JobBuilderFactory jobBuilderFactory;
@Autowired
private StepBuilderFactory stepBuilderFactory;
@Bean
public Tasklet tasklet() {
return new Tasklet() {
@Override
public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception {
System.out.println("--------tasklet------------");
return RepeatStatus.FINISHED;
}
};
}
@Bean
public Step step() {
return stepBuilderFactory.get("stepOne")
.tasklet(tasklet())
.build();
}
@Bean
public Job job() {
return jobBuilderFactory.get("job")
.start(step())
.build();
}
}