Spring Boot 集成Spring Batch:实现批处理任务
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.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.item.ItemWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class BatchExampleApplication {
@Autowired
private JobBuilderFactory jobBuilderFactory;
@Autowired
private StepBuilderFactory stepBuilderFactory;
@Autowired
private JobLauncher jobLauncher;
// 定义Tasklet任务
@Bean
public Tasklet tasklet() {
return new Tasklet() {
@Override
public ExitStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
// 你的任务逻辑
System.out.println("Tasklet is running...");
return ExitStatus.COMPLETED;
}
};
}
// 定义ItemWriter
@Bean
public ItemWriter<String> itemWriter() {
return items -> {
for (String item : items) {
// 你的写入逻辑
System.out.println("Writing item: " + item);
}
};
}
// 创建一个Step
@Bean
public Step step() {
return stepBuilderFactory.get("step")
.tasklet(tasklet())
.build();
}
// 创建一个Job
@Bean
public Job job() {
return jobBuilderFactory.get("job")
.start(step())
.build();
}
public static void main(String[] args) {
SpringApplication.run(BatchExampleApplication.class, args);
}
}
这个简单的Spring Batch示例展示了如何在Spring Boot应用程序中定义一个简单的批处理作业。它包括一个任务(Tasklet)和一个步骤(Step),并且可以通过Spring Boot应用程序的main方法启动。这个例子旨在教育开发者如何在Spring Boot中设置和运行批处理作业。
评论已关闭