下面详细讲解Spring Batch入门示例的完整攻略,内容包括:
- Spring Batch 简介
- Spring Batch 入门示例概述
- 示例1:批处理读取 CSV 文件并输出到控制台
- 示例2:批处理读取数据库中的数据并写入到 XML 文件中
Spring Batch 简介
Spring Batch 是一个高效、强大、可重用的批处理框架,能够处理海量的数据量。Spring Batch 建立在 Spring 框架之上,可以轻松地集成 Spring 生态系统的其他工具和框架,如 Spring Boot、Spring Data 和 Spring Integration 等。
Spring Batch 支持以下功能:
- 大批量处理任务
- 失败重试机制
- 多线程并发处理
- 分布式处理
- 报告和统计
Spring Batch 入门示例概述
Spring Batch 入门示例主要包括以下内容:
- 创建 Spring Batch 项目和 Maven 依赖
- 编写 Job、Step、Reader、Processor 和 Writer
- 运行 Spring Batch 示例
下面,我将分别介绍示例1和示例2的具体实现。
示例1:批处理读取 CSV 文件并输出到控制台
创建 Spring Batch 项目和 Maven 依赖
首先,我们需要创建一个基于 Maven 的 Spring Batch 项目,并添加以下 Maven 依赖:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-batch</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.batch</groupId>
<artifactId>spring-batch-core</artifactId>
<version>4.3.3</version>
</dependency>
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>5.2</version>
</dependency>
</dependencies>
编写 Job、Step、Reader、Processor 和 Writer
在 src/main/java 目录下创建 com.example.batch 包,并添加以下类:
- Student.java(实体类)
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class Student {
private String name;
private String gender;
private int age;
private String classNo;
}
- CsvItemReader.java(CSV 文件读取器)
@Component
public class CsvItemReader extends FlatFileItemReader<Student> {
public CsvItemReader() {
setLinesToSkip(1); // 跳过表头
setResource(new ClassPathResource("students.csv")); // CSV 文件路径
setLineMapper(new DefaultLineMapper<Student>() {{
setLineTokenizer(new DelimitedLineTokenizer("|") {{
setNames(new String[]{"name", "gender", "age", "classNo"}); // CSV 文件中每一列对应实体类的属性
}});
setFieldSetMapper(new BeanWrapperFieldSetMapper<Student>() {{
setTargetType(Student.class);
}});
}});
}
}
- StudentItemProcessor.java(数据处理器)
@Component
public class StudentItemProcessor implements ItemProcessor<Student, Student> {
@Override
public Student process(Student student) throws Exception {
student.setName(student.getName().toUpperCase()); // 将姓名转换为大写
student.setAge(student.getAge() + 1); // 年龄加1
return student;
}
}
- ConsoleItemWriter.java(输出到控制台)
@Component
public class ConsoleItemWriter implements ItemWriter<Student> {
@Override
public void write(List<? extends Student> students) throws Exception {
for (Student student : students) {
System.out.println(student);
}
}
}
- BatchConfig.java(Spring Batch 配置类)
@Configuration
@EnableBatchProcessing
public class BatchConfig {
@Autowired
private JobBuilderFactory jobBuilderFactory;
@Autowired
private StepBuilderFactory stepBuilderFactory;
@Autowired
private CsvItemReader csvItemReader;
@Autowired
private StudentItemProcessor studentItemProcessor;
@Autowired
private ConsoleItemWriter consoleItemWriter;
@Bean
public Job job() {
return jobBuilderFactory.get("job")
.incrementer(new RunIdIncrementer())
.start(step())
.build();
}
@Bean
public Step step() {
return stepBuilderFactory.get("step")
.<Student, Student>chunk(10)
.reader(csvItemReader)
.processor(studentItemProcessor)
.writer(consoleItemWriter)
.build();
}
}
运行 Spring Batch 示例
在 resources 目录下添加 students.csv,文件内容如下:
name|gender|age|classNo
张三|男|20|001
李四|女|22|002
王五|男|21|003
赵六|女|19|004
运行 com.example.batch.SpringBatchExampleApplication 类的 main 方法即可运行示例1。
示例2:批处理读取数据库中的数据并写入到 XML 文件中
创建 Spring Batch 项目和 Maven 依赖
首先,我们需要创建一个基于 Maven 的 Spring Batch 项目,并添加以下 Maven 依赖:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-batch</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.batch</groupId>
<artifactId>spring-batch-core</artifactId>
<version>4.3.3</version>
</dependency>
<dependency>
<groupId>org.springframework.batch</groupId>
<artifactId>spring-batch-infrastructure</artifactId>
<version>4.3.3</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.5</version>
</dependency>
</dependencies>
编写 Job、Step、Reader、Processor 和 Writer
在 src/main/java 目录下创建 com.example.batch 包,并添加以下类:
- User.java(实体类)
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class User {
private int id;
private String name;
private int age;
}
- UserItemReader.java(数据库读取器)
@Component
public class UserItemReader extends MyBatisCursorItemReader<User> {
public UserItemReader(SqlSessionFactory sqlSessionFactory) {
setSqlSessionFactory(sqlSessionFactory);
setQueryId("com.example.batch.mapper.UserMapper.selectAll"); // 调用 UserMapper 接口查询所有用户
}
}
- UserItemProcessor.java(数据处理器)
@Component
public class UserItemProcessor implements ItemProcessor<User, User> {
@Override
public User process(User user) throws Exception {
user.setName("Hello, " + user.getName()); // 姓名添加前缀
user.setAge(user.getAge() + 1); // 年龄加1
return user;
}
}
- XmlItemWriter.java(写入 XML 文件)
@Component
public class XmlItemWriter extends StaxEventItemWriter<User> {
public XmlItemWriter() throws IOException {
setRootTagName("users");
setResource(new FileSystemResource("users.xml")); // 输出的 XML 文件路径
setMarshaller(getMarshaller());
}
private Marshaller getMarshaller() throws IOException {
XStreamMarshaller marshaller = new XStreamMarshaller();
marshaller.setAliases(Collections.singletonMap("user", User.class));
marshaller.afterPropertiesSet();
return marshaller;
}
}
- BatchConfig.java(Spring Batch 配置类)
@Configuration
@EnableBatchProcessing
@MapperScan(basePackages = "com.example.batch.mapper")
public class BatchConfig {
@Autowired
private JobBuilderFactory jobBuilderFactory;
@Autowired
private StepBuilderFactory stepBuilderFactory;
@Autowired
private SqlSessionFactory sqlSessionFactory;
@Autowired
private UserItemReader userItemReader;
@Autowired
private UserItemProcessor userItemProcessor;
@Autowired
private XmlItemWriter xmlItemWriter;
@Bean
public Job job() {
return jobBuilderFactory.get("job")
.incrementer(new RunIdIncrementer())
.start(step())
.build();
}
@Bean
public Step step() {
return stepBuilderFactory.get("step")
.<User, User>chunk(10)
.reader(userItemReader)
.processor(userItemProcessor)
.writer(xmlItemWriter)
.build();
}
}
运行 Spring Batch 示例
创建数据库和表,并插入数据:
CREATE DATABASE springbatch
USE springbatch
CREATE TABLE user (
id INT PRIMARY KEY,
name VARCHAR(20),
age INT
)
INSERT INTO user VALUES
(1, '张三', 20),
(2, '李四', 22),
(3, '王五', 21),
(4, '赵六', 19)
运行 com.example.batch.SpringBatchExampleApplication 类的 main 方法即可运行示例2。
以上就是 Spring Batch 入门示例的完整攻略,希望对你有所帮助。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Spring Batch 入门示例 - Python技术站