Spring Boot实战:通过Spring Batch处理批量订单数据

引言

Spring Batch 提供了一个强大的基础设施来支持创建健壮的批处理应用。它包括以下关键特性:

  • 可扩展性:可以轻松扩展以适应各种规模的数据集。
  • 事务管理:确保数据完整性,支持重试和回滚机制。
  • 监控和日志:提供了详细的执行报告和日志记录功能。

2. 准备环境

为了构建我们的示例项目,我们需要先设置好开发环境。这里假设你已经安装了 Java 和 Maven,并且熟悉 Spring Boot。

依赖添加

首先,在 pom.xml 文件中添加 Spring Boot Starter Batch 依赖:

复制代码
xml

深色版本

复制代码
1<dependencies>
2    <dependency>
3        <groupId>org.springframework.boot</groupId>
4        <artifactId>spring-boot-starter-batch</artifactId>
5    </dependency>
6    <!-- 其他可能需要的依赖,例如数据库驱动 -->
7</dependencies>

配置文件

在 application.properties 文件中添加数据库连接配置:

复制代码
properties

深色版本

复制代码
1spring.datasource.url=jdbc:mysql://localhost:3306/ordersdb
2spring.datasource.username=root
3spring.datasource.password=password
4spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
5spring.jpa.hibernate.ddl-auto=update

3. 数据模型

我们先定义一个简单的订单实体类:

复制代码
java

深色版本

复制代码
1import javax.persistence.Entity;
2import javax.persistence.GeneratedValue;
3import javax.persistence.GenerationType;
4import javax.persistence.Id;
5
6@Entity
7public class Order {
8    @Id
9    @GeneratedValue(strategy = GenerationType.AUTO)
10    private Long id;
11    private String orderNumber;
12    private String customerName;
13    private double totalAmount;
14
15    // Getters and setters
16}

4. 创建批量任务

接下来,我们将定义一个批量任务来处理订单数据。

Step Configuration

定义一个步骤来读取、处理并写入订单数据:

复制代码
java

深色版本

复制代码
1import org.springframework.batch.core.Step;
2import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
3import org.springframework.batch.item.database.JpaItemWriter;
4import org.springframework.batch.item.file.FlatFileItemReader;
5import org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper;
6import org.springframework.batch.item.file.mapping.DefaultLineMapper;
7import org.springframework.batch.item.file.transform.DelimitedLineTokenizer;
8import org.springframework.context.annotation.Bean;
9import org.springframework.context.annotation.Configuration;
10import org.springframework.core.io.ClassPathResource;
11
12@Configuration
13public class BatchConfig {
14
15    @Bean
16    public FlatFileItemReader<Order> orderReader() {
17        FlatFileItemReader<Order> reader = new FlatFileItemReader<>();
18        reader.setResource(new ClassPathResource("orders.csv"));
19        reader.setLineMapper(new DefaultLineMapper<Order>() {{
20            setLineTokenizer(new DelimitedLineTokenizer() {{
21                setNames(new String[] {"orderNumber", "customerName", "totalAmount"});
22            }});
23            setFieldSetMapper(new BeanWrapperFieldSetMapper<Order>() {{
24                setTargetType(Order.class);
25            }});
26        }});
27        return reader;
28    }
29
30    @Bean
31    public JpaItemWriter<Order> orderWriter() {
32        return new JpaItemWriter<>();
33    }
34
35    @Bean
36    public Step step1(StepBuilderFactory stepBuilderFactory) {
37        return stepBuilderFactory.get("step1")
38                .<Order, Order>chunk(10)
39                .reader(orderReader())
40                .writer(orderWriter())
41                .build();
42    }
43}

Job Configuration

定义一个作业来启动步骤:

复制代码
java

深色版本

复制代码
1import org.springframework.batch.core.Job;
2import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
3import org.springframework.context.annotation.Bean;
4import org.springframework.context.annotation.Configuration;
5
6@Configuration
7public class JobConfig {
8
9    @Bean
10    public Job importUserJob(JobBuilderFactory jobBuilderFactory,
11                             Step step1) {
12        return jobBuilderFactory.get("importUserJob")
13                .start(step1)
14                .build();
15    }
16}

5. 运行作业

最后,我们需要一个主类来启动 Spring Boot 应用,并触发作业执行:

复制代码
java

深色版本

复制代码
1import org.springframework.boot.SpringApplication;
2import org.springframework.boot.autoconfigure.SpringBootApplication;
3import org.springframework.context.ConfigurableApplicationContext;
4
5@SpringBootApplication
6public class BatchApplication {
7
8    public static void main(String[] args) throws Exception {
9        ConfigurableApplicationContext context = SpringApplication.run(BatchApplication.class, args);
10        context.getBean(JobLauncher.class).run(context.getBean(Job.class), new JobParameters());
11    }
12}

6. 结论

本教程展示了如何使用 Spring Boot 和 Spring Batch 构建一个简单的批量处理系统,用于导入 CSV 文件中的订单数据到数据库。你可以根据实际业务需求进一步扩展和定制这些组件。

希望这个示例能够帮助你快速入门 Spring Batch,并为你的项目带来价值。如果你有任何问题或反馈,请随时留言!

相关推荐
通往曙光的路上31 分钟前
焚决糟糕篇
java·spring boot·tomcat
6***v41733 分钟前
spring boot 项目打印sql日志和结果,使用logback或配置文件
spring boot·sql·logback
3***g2051 小时前
如何使用Spring Boot框架整合Redis:超详细案例教程
spring boot·redis·后端
s***35301 小时前
Spring Boot3.x集成Flowable7.x(一)Spring Boot集成与设计、部署、发起、完成简单流程
java·spring boot·后端
3***16101 小时前
【监控】Spring Boot+Prometheus+Grafana实现可视化监控
spring boot·grafana·prometheus
s***4531 小时前
SpringBoot返回文件让前端下载的几种方式
前端·spring boot·后端
大云计算机毕设3 小时前
【2026计算机毕设选题】计算机毕设全新推荐项目选题指南(70+精选热门方向)
spring·数据分析·毕业设计·课程设计·毕设
空空kkk3 小时前
SpringMVC——拦截器
java·数据库·spring·拦截器
梵得儿SHI3 小时前
(第七篇)Spring AI 基础入门总结:四层技术栈全景图 + 三大坑根治方案 + RAG 进阶预告
java·人工智能·spring·springai的四大核心能力·向量维度·prompt模板化·向量存储检索
i***27953 小时前
Spring boot 3.3.1 官方文档 中文
java·数据库·spring boot