Spring Boot下Spring Batch入门实例
一、About
Spring Batch是什么能干什么,网上一搜就有,但是就是没有入门实例,能找到的例子也都是2.0的,看文档都是英文无从下手~~~,使用当前最新的版本整合网络上找到的例子。
关于基础不熟悉的,推荐读一下Spring Batch 批处理框架这本书,虽然讲的是2.0但基本概念没变。
1.1 How Spring Batch works?

一个Job有1个或多个Step组成,Step有读、处理、写三部分操作组成;通过JobLauncher启动Job,启动时从JobRepository获取Job Execution;当前运行的Job及Step的结果及状态保存在JobRepository中。
二、Begin
下面举个小例子,就是这篇文章中的例子,下面的这个例子版本是最新的:
- spring-boot:2.0.1.RELEASE
- spring-batch-4.0.1.RELEASE(Spring-Boot 2.0.1就是依赖的此版本)
下面这个例子实现的是:从变量中读取3个字符串全转化大写并输出到控制台,加了一个监听,当任务完成时输出一个字符串到控制台,通过web端来调用。
下面是项目的目录结构:

2.1 pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.javainuse</groupId>
<artifactId>springboot-batch</artifactId>
<version>0.0.1</version>
<packaging>jar</packaging>
<name>SpringBatch</name>
<description>Spring Batch-Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.1.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-batch</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2.2 Item Reader
读取:从数组中读取3个字符串
package com.javainuse.step;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.NonTransientResourceException;
import org.springframework.batch.item.ParseException;
import org.springframework.batch.item.UnexpectedInputException;
public class Reader implements ItemReader<String> {
private String[] messages = { "javainuse.com",
"Welcome to Spring Batch Example",
"We use H2 Database for this example" };
private int count = 0;
@Override
public String read() throws Exception, UnexpectedInputException, ParseException, NonTransientResourceException {
if (count < messages.length) {
return messages[count++];
} else {
count = 0;
}
return null;
}
}
2.3 Item Processor
处理:将字符串转为大写
package com.javainuse.step;
import org.springframework.batch.item.ItemProcessor;
public class Processor implements ItemProcessor<String, String> {
@Override
public String process(String data) throws Exception {
return data.toUpperCase();
}
}
2.4 Item Writer
输出:把转为大写的字符串输出到控制台
package com.javainuse.step;
import java.util.List;
import org.springframework.batch.item.ItemWriter;
public class Writer implements ItemWriter<String> {
@Override
public void write(List<? extends String> messages) throws Exception {
for (String msg : messages) {
System.out.println("Writing the data " + msg);
}
}
}
2.5 Listener
监听:任务成功完成后往控制台输出一行字符串
package com.javainuse.listener;
import org.springframework.batch.core.BatchStatus;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.listener.JobExecutionListenerSupport;
public class JobCompletionListener extends JobExecutionListenerSupport {
@Override
public void afterJob(JobExecution jobExecution) {
if (jobExecution.getStatus() == BatchStatus.COMPLETED) {
System.out.println("BATCH JOB COMPLETED SUCCESSFULLY");
}
}
}
2.6 Config
Spring Boot配置:
package com.javainuse.config;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecutionListener;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.javainuse.listener.JobCompletionListener;
import com.javainuse.step.Processor;
import com.javainuse.step.Reader;
import com.javainuse.step.Writer;
@Configuration
public class BatchConfig {
@Autowired
public JobBuilderFactory jobBuilderFactory;
@Autowired
public StepBuilderFactory stepBuilderFactory;
@Bean
public Job processJob() {
return jobBuilderFactory.get("processJob")
.incrementer(new RunIdIncrementer()).listener(listener())
.flow(orderStep1()).end().build();
}
@Bean
public Step orderStep1() {
return stepBuilderFactory.get("orderStep1").<String, String> chunk(1)
.reader(new Reader()).processor(new Processor())
.writer(new Writer()).build();
}
@Bean
public JobExecutionListener listener() {
return new JobCompletionListener();
}
}
2.7 Controller
控制器:配置web路由,访问/invokejob来调用任务
package com.javainuse.controller;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class JobInvokerController {
@Autowired
JobLauncher jobLauncher;
@Autowired
Job processJob;
@RequestMapping("/invokejob")
public String handle() throws Exception {
JobParameters jobParameters = new JobParametersBuilder().addLong("time", System.currentTimeMillis())
.toJobParameters();
jobLauncher.run(processJob, jobParameters);
return "Batch job has been invoked";
}
}
2.8 application.properties
配置:Spring Batch在加载的时候job默认都会执行,把spring.batch.job.enabled置为false,即把job设置成不可用,应用便会根据jobLauncher.run来执行。下面2行是数据库的配置,不配置也可以,使用的嵌入式数据库h2
spring.batch.job.enabled=false
spring.datasource.url=jdbc:h2:file:./DB
spring.jpa.properties.hibernate.hbm2ddl.auto=update
2.9 Application
Spring Boot入口类:加注解@EnableBatchProcessing
package com.javainuse;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@EnableBatchProcessing
public class SpringBatchApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBatchApplication.class, args);
}
}
三、Run
启动这个Spring Boot项目,访问下面这个路径,会有如下输出
http://localhost:8080/invokejob

然后控制台会有如下输出:

我们可以使用H2-console来查看H2数据库,访问如下地址 http://localhost:8080/h2-console , 选择如下数据库,输入JDBC URL:jdbc:h2:file:./DB,这是上文配置的,不用输入密码,直接点击Connect就可以了。

连上后显示如下:

左侧那些表就是Spring Batch自动创建的,至于每个表都是什么意思,可参考下面的那本书,这些建表的脚本存在于哪呢?可在spring-batch-core-xxx.jar包下的org.springframework.batch.core包下找到


查看batch-h2.properties可以看到相关的默认配置:

四、Reference
- Spring Boot Batch Job Simple Example
- Implement Spring Batch using Spring Boot-Hello World Example
- Spring Batch 批处理框架
- springboot-batch 实例源码
Spring Boot下Spring Batch入门实例的更多相关文章
- spring boot 下 spring security 自定义登录配置与form-login属性详解
package zhet.sprintBoot; import org.springframework.beans.factory.annotation.Autowired;import org.sp ...
- Spring Boot 2.x 快速入门(下)HelloWorld示例详解
上篇 Spring Boot 2.x 快速入门(上)HelloWorld示例 进行了Sprint Boot的快速入门,以实际的示例代码来练手,总比光看书要强很多嘛,最好的就是边看.边写.边记.边展示. ...
- Spring Boot微服务架构入门
概述 还记得在10年毕业实习的时候,当时后台三大框架为主流的后台开发框架成软件行业的标杆,当时对于软件的认识也就是照猫画虎,对于为什么会有这么样的写法,以及这种框架的优势或劣势,是不清楚的,Sprin ...
- Spring Boot从入门到精通之:一、Spring Boot简介及快速入门
Spring Boot Spring Boot 简介 Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该框架使用了特定的方式来 ...
- Spring Boot 2.x 快速入门(上)HelloWorld示例
本文重点 最近决定重新实践下Spring Boot的知识体系,因为在项目中遇到的总是根据业务需求走的知识点,并不能覆盖Spring Boot完整的知识体系,甚至没有一个完整的实践去实践某个知识点.最好 ...
- Spring Boot 如何极简入门?
Spring Boot已成为当今最流行的微服务开发框架,本文是如何使用Spring Boot快速开始Web微服务开发的指南,我们将创建一个可运行的包含内嵌Web容器(默认使用的是Tomcat)的可运行 ...
- Spring boot项目搭建及简单实例
Spring boot项目搭建 Spring Boot 概述 Build Anything with Spring Boot:Spring Boot is the starting point for ...
- Spring Boot 缓存应用 Ehcache 入门教程
Ehcache 小巧轻便.具备持久化机制,不用担心JVM和服务器重启的数据丢失.经典案例就是著名的Hibernate的默认缓存策略就是用Ehcache,Liferay的缓存也是依赖Ehcache. 本 ...
- spring boot集成redis基础入门
redis 支持持久化数据,不仅支持key-value类型的数据,还拥有list,set,zset,hash等数据结构的存储. 可以进行master-slave模式的数据备份 更多redis相关文档请 ...
随机推荐
- STM32 中的 assert_param 函数
在学STM32的时候函数assert_param出现的几率非常大,上网搜索一下,网上一般解释断言机制,做为程序开发调试阶段时使用. 断言机制函数assert_param我们在分析库函数的时候,几乎每一 ...
- stylus css tooltips 工具提示
tooltips 纯css工具提示 bubbles-tooltips 查看效果 演示 安装 npm install tooltips --save 使用 在 gulp 中使用 gulp var gul ...
- 浏览器中唤起native app || 跳转到应用商城下载
前段时间遇到一个小需求:要求在分享出来的h5页面中,有一个立即打开的按钮,如果本地安装了我们的app,那么点击就直接唤起本地app,如果没有安装,则跳转到下载. 因为从来没有做过这个需求,因此这注定是 ...
- 摩拜单车微信小程序开发技术总结
前言 摩拜单车小程序已于微信小程序上线第一天正式发布,刷爆微博媒体朋友圈.本文主要讲讲技术方向的总结,在段时间的开发周期内内如何一步步从学习到进阶. 思维转变 微信小程序没有HTML的常用标签,而是类 ...
- 3天时间从零到上架AppStore流程记录
3天时间从零到上架AppStore流程记录 清明假期刚过去一周,我如愿以偿把自己想要的一个App上架了AppStore 从有idea到技术选型,从设计稿到框架开发,从提审AppStore到上架一共经历 ...
- Zabbix-Proxy 部署和运行
Zabbix-Proxy 部署&运行 前提 版本: zabbix-server 5.4 任务: 通过SNMP监控网络设备,需要需通过zabbix-proxy 发送到zabbix-server. ...
- uniapp中添加vant组件
首先是npm i vant@2 -S 下载vant包 接下来就是找到main.js引入vant 然后就是在页面中直接使用 会发现没有样式 最后再找到app.vue再style里面全局引入vant的样式 ...
- switch 和 if else if else 有什么区别
1. 一般情况下,它们两个语句可以相互替换 2. switch..case语句通常处理case为比较确定值的情况,而if...else...语句更加灵活,常用于范围判断(大于.等于某个范围) 3. ...
- SQLAlchemy加载数据到数据库
SQLAlchemy加载数据到数据库 最近在研究基于知识图谱的问答系统,想要参考网上分享的关于NLPCC 2016 KBQA任务的经验帖,自己实现一个原型.不少博客都有提到,nlpcc-kbqa训练数 ...
- AQS源码阅读
简介 AQS 全程为 AbstractQueuedSynchronizer , 在 java.util.concurrent.locks包下的一个抽象类. 类的具体作用以及设计在开始类描述信息里面就有 ...