Spring 批处理事务管理 - 多线程步骤

Spring Batch Transaction Management - Multi Threaded Step

我在批处理作业中使用多线程步骤来处理来自源数据库的记录并写入目标数据库。 Step 是基于块的,由 JdbcpagingItemReader、Processor 和 JdbcBathItemWriter 组成。我知道如果在 Step 处理期间发生任何异常,数据库事务会为整个块回滚。我想了解内部如何在 Spring 批处理中进行管理?由于这是多线程步骤,因此无法保证处理器和写入器在块的同一线程中执行。块可能会被不同的线程处理。那么 Spring 批处理如何确保数据库事务正确回滚,即使不同的线程正在处理同一个块?

您的说法不正确:"The chunk may get processed by different Threads."

参考 Spring 批处理文档,关于 Multi-threaded Step,步骤通过在单独的执行线程中读取、处理和写入每个项目块来执行。所以多线程是在 步级别而不是块级别 启用的,并且它在自己的线程中执行每个块;因此每个线程将是“运行”一个read-process-write组合。

The result of the above configuration is that the Step executes by reading, processing, and writing each chunk of items (each commit interval) in a separate thread of execution. Note that this means there is no fixed order for the items to be processed, and a chunk might contain items that are non-consecutive compared to the single-threaded case. In addition to any limits placed by the task executor (such as whether it is backed by a thread pool), there is a throttle limit in the tasklet configuration which defaults to 4. You may need to increase this to ensure that a thread pool is fully utilized.

因此,由于每个块都在专用线程上运行,因此事务管理非常简单。

请使用本地分区这将使您完全控制执行并让您清楚地了解每个工作线程reader+处理器+编写器事务,回滚批提交和异常处理(您可以添加侦听器)

https://docs.spring.io/spring-batch/docs/current/reference/html/scalability.html#partitioning

我们已经在数百万条记录的项目中使用过,处理性能是最终的,完全控制工作线程。它确实是一个很棒的框架,大部分批处理问题都在内部处理,我们不必担心。让我们知道,您需要样品吗?