返回首页

Spring Batch 用于无超时的 Excel 报表

本文描述了使用 Spring Batch 实现异步批量 Excel 报表生成的实现。PRINT、ZIP、UPLOAD、CLEAN_UP 步骤的代码示例详解。与前端进度集成以及通过 Thread Pool 扩展。

批量 Excel 生成:Spring Batch 在生产环境中的应用
Advertisement 728x90

使用Spring Batch批量处理Excel报告:架构与实现

Spring Batch解决了在单个HTTP请求中同步生成数百个Excel文档的问题。该框架将流程分解为多个块,管理状态,并确保从故障中恢复。在一个自动化飞机发动机维修的实际项目中,这使用户能够触发工作卡和路线表的批量打印,而不会超时。

Spring Batch的核心组件

Job 协调整个周期:Excel生成、归档、存储上传和清理。Step 是一个处理阶段,Tasklet 是一个原子操作。

流程分为面向块的步骤(批量读取/处理/写入)和基于Tasklet的步骤(单一操作)。这确保了阶段的独立性和集中管理。

Google AdInline article slot

报告生成的步骤

步骤 PRINT:创建Excel文件

数据被分成每10项一个块。每个块通过读取器 → 处理器 → 写入器:

@Bean
@JobScope
public Step printTrpTagsStep(
        ItemReader<TrpTagForPrintModel> excelTrpTagItemReader,
        ItemProcessor<TrpTagForPrintModel, ExcelItem> excelTrpTagItemProcessor,
        ItemWriter<ExcelItem> excelTrpTagItemWriter
) {
    return new StepBuilder(BatchExcelPrintStep.PRINT.getCode(), jobRepository)

            .<TrpTagForPrintModel, ExcelItem>chunk(10)
                    .transactionManager(transactionManager)
                    .reader(excelTrpTagItemReader)
                    .processor(excelTrpTagItemProcessor)
                    .writer(excelTrpTagItemWriter)
                    .build();
}

Spring Batch跟踪writeCount以监控进度。文件保存到/tmp/engine/{timestamp}/zip/,并按文档类型创建子文件夹。

步骤 ZIP:创建归档文件

一个Tasklet扫描目录并使用标准Java工具创建ZIP文件。

Google AdInline article slot

步骤 UPLOAD:上传到S3

归档文件上传到S3,链接记录在ExecutionContext中。

步骤 CLEAN_UP:清理临时数据

JobExecutionListener检查状态,并在成功或失败时清理/tmp目录。

并发与扩展

多个Job在线程池中启动,以处理并发用户请求。在一个Job内,未使用并行步骤,但框架支持此功能。

Google AdInline article slot

前端集成:监控进度

POST /trp-tag/print/excel/batch/start 返回一个jobExecutionId。GET /trp-tag/print/excel/batch/{id} 返回状态。

进度计算如下:

  • PRINT:与writeCount成比例(占90%的时间)。
  • 剩余步骤:0%或100%。

前端接收:

  • progressPercentage 用于进度条。
  • currentStepNumber/totalStepsNumber。
  • status(STARTED/COMPLETED/FAILED)。
  • downloadUrl。
  • failureDetails。
  • durationMillis。

实现优势

  • 异步处理:即时响应,避免超时。
  • 持久化:历史记录存储在PostgreSQL中,无需额外基础设施。
  • 事务完整性:自动状态管理,不同于@Async。

关键要点

  • 块大小为10可最小化内存使用并确保进度跟踪。
  • WriteCount是用于精确监控的内置计数器。
  • ExecutionContext存储工件引用。
  • JobExecutionListener保证清理。
  • 线程池可并发扩展多个Job。

Spring Batch适用于任何需要归档和存储的批量文档生成。实现时间少于使用队列的自定义逻辑。

— Editorial Team

Advertisement 728x90

继续阅读