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相关文档请 ...
随机推荐
- 决策树算法一:hunt算法,信息增益(ID3)
决策树入门 决策树是分类算法中最重要的算法,重点 决策树算法在电信营业中怎么工作? 这个工人也是流失的,在外网转移比处虽然没有特征来判断,但是在此节点处流失率有三个分支概率更大 为什么叫决策树? 因为 ...
- C/C++头文件以及避免头文件包含造成的重定义方法
C 头文件 头文件是扩展名为 .h 的文件,包含了 C 函数声明和宏定义,被多个源文件中引用共享.有两种类型的头文件:程序员编写的头文件和编译器自带的头文件. 在程序中要使用头文件,需要使用 C 预处 ...
- 顺利通过EMC实验(10)
- HTTP权威指南:第二章
URL概览 前面提到,URL资源是HTTP协议所使用的寻找资源位置的定位符.分为三个部分,主要的结构是: 方案://服务器/路径 这种结构使得网络上的每一个资源都只有唯一的命名方法,从而使得浏览器可以 ...
- canvas菜鸟基于小程序实现图案在线定制功能
前言 最近收到一个这样的需求,要求做一个基于 vue 和 element-ui 的通用后台框架页,具体要求如下: 要求通用性高,需要在后期四十多个子项目中使用,所以大部分地方都做成可配置的. 要求做成 ...
- java的命令行参数到底怎么用,请给截图和实际的例子
8.2 命令行参数示例(实验) public class Test { public static void main(String[] args){ if(args.length ...
- linux设备管理之主设备号与次设备号
主设备号和次设备号 一个字符设备或者块设备都有一个主设备号和次设备号.主设备号和次设备号统称为设备号.主设备号用来表示一个特定的驱动程序.次设备号用来表示使用该驱动程序的其他设备.(主设备号和控制这类 ...
- 虚拟机安装linux
https://blog.csdn.net/wujiele/article/details/92803655https://www.cnblogs.com/yunwangjun-python-520/ ...
- 在UnityUI中绘制线状统计图2.0
##在之前的基础上添加横纵坐标 上一期在这里:https://www.cnblogs.com/AlphaIcarus/p/16123434.html 先分别创建横纵坐标点的模板,将这两个Text放在G ...
- css 实现流光字体效果
<template> <div> <p data-text="Lorem ipsum dolor"> Lorem ipsum dolor ...