我目前正在研究 Spring Batch 实现,在学习 YouTube 上名为“高性能批处理”的教程时遇到了问题。本教程建议使用“AsyncItemProcessor 和 AsyncItemWriter”进行缩放,但我注意到类 AsyncItemProcessor 和 AsyncItemWriter 在最新版本的 Spring Batch 中不再存在。
我广泛搜索了解决方案,检查了视频和迁移指南,但没有找到任何有关实现异步项目处理和写入的指南。
有人可以提供有关如何在 Spring Batch 中实现异步项目处理和编写的帮助吗?
提前感谢您的帮助!
配置读取器、处理器和写入器:
@Configuration
public class ItemConfig {
@Autowired
private EntityManagerFactory entityManagerFactory;
@Bean
public JpaPagingItemReader<Employee> itemReader() {
JpaPagingItemReaderBuilder<Employee> reader = new JpaPagingItemReaderBuilder<>();
reader.entityManagerFactory(entityManagerFactory);
reader.pageSize(1000);
reader.queryString("SELECT e FROM employees e");
reader.name("itemReader");
return reader.build();
}
@Bean
public ItemProcessor<Employee, Employee> processor() {
return new ItemProcessorImpl();
}
@Bean
public ItemWriter<Employee> itemWriter() {
final JpaItemWriter<Employee> writer = new JpaItemWriter<>();
writer.setEntityManagerFactory(entityManagerFactory);
return writer;
}
}
配置作业和步骤:
@Configuration
public class BatchConfig {
@Bean
public Job job(JobRepository jobRepository, Step step) {
return new JobBuilder("job", jobRepository)
.start(step)
.build();
}
@Bean
public Step step(JobRepository jobRepository,
PlatformTransactionManager transactionManager,
JpaPagingItemReader<Employee> itemReader,
ItemProcessor<Employee, Employee> processor,
ItemWriter<Employee> itemWriter) {
return new StepBuilder("step", jobRepository)
.<Employee, Employee>chunk(1000, transactionManager)
.reader(itemReader)
.processor(processor)
.writer(itemWriter)
.build();
}
}
类
AsyncItemProcessor
和 AsyncItemWriter
包含在 jar spring-batch-integration
中。您需要将其添加到您的项目中。如果您使用 Spring Boot 和 Maven,那么您可以使用以下代码片段:
<dependency>
<groupId>org.springframework.batch</groupId>
<artifactId>spring-batch-integration</artifactId>
</dependency>
默认情况下,带有 Spring Batch 的 Spring Boot 应用程序仅使用用于
spring-batch-core
、spring-batch-infrastructure
和测试 spring-batch-test
的 jar。