这是我的 spring 批处理配置:
@RequiredArgsConstructor
@Configuration
@Slf4j
@EnableBatchProcessing
public class SpringBatchConfig {
private final JobBuilderFactory jobBuilderFactory;
private final StepBuilderFactory stepBuilderFactory;
@Autowired
@Lazy
private CRMTService crmtService;
@Bean
public TaskExecutor myTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10);
executor.setMaxPoolSize(15);
executor.setQueueCapacity(100);
executor.setThreadNamePrefix("Batch-");
executor.initialize();
return executor;
}
@Bean
public Step step() {
return stepBuilderFactory.get("step")
.<String, String>chunk(10)
.reader(itemReader())
.processor(itemProcessor())
.writer(itemWriter())
.taskExecutor(myTaskExecutor())
.build();
}
@Bean
public Job job() {
return jobBuilderFactory.get("job")
.start(step())
.build();
}
@Bean
@StepScope
public ItemReader<String> itemReader() {
List<String> list = crmtService.getVertrags();
return new IteratorItemReader<>(list != null ? list.iterator() : Collections.emptyIterator());
}
@Bean
@StepScope
public ItemProcessor<String, String> itemProcessor() {
return item -> {
//Logic -> This calls a method in service class. In that method I am calling an API for each string and saving the response to mongodb.
return item;
};
}
@Bean
@StepScope
public ItemWriter<String> itemWriter() {
return items -> {
//If we plan to log do anything in future
};
}
}
JDK版本11
Spring引导版本2.6.3
我正在我的服务类别中触发这个春季批次。
当我不使用任务执行器时,我能够获取 mongodb 中的所有产品(214)[使用单线程我能够获取所有产品,但显然这需要时间]。当我与任务执行器一起使用时,我错过了 1 或 2 个产品 (212/213)。
此外,还有两个有趣的观察结果:
当触发 Spring Batch 时,这些是我在控制台中收到的日志:
WARN [] 9758 --- [onPool-worker-1] o.s.b.c.c.a.DefaultBatchConfigurer : No datasource was provided...using a Map based JobRepository
WARN [] 9758 --- [onPool-worker-1] o.s.b.c.c.a.DefaultBatchConfigurer : No transaction manager was provided, using a ResourcelessTransactionManager
INFO [] 9758 --- [onPool-worker-1] o.s.b.c.l.support.SimpleJobLauncher : **No TaskExecutor has been set, defaulting to synchronous executor**.
尽管我已经在步骤bean中设置了任务执行器。我收到这条消息。
当 Spring Batch 实际启动时,正在运行的线程来自 myTaskExecutor”,因为在控制台中我可以看到线程的名称以“Batch”开头,这是我在 Spring Batch 配置类中添加的前缀。
[ Batch-1] c.t.openapi.crmt.conf.SpringBatchConfig : Processing 123
[ Batch-3] c.t.openapi.crmt.conf.SpringBatchConfig : Processing 456
[ Batch-2] c.t.openapi.crmt.conf.SpringBatchConfig : Processing 789
问题1:为什么我明确定义了任务执行器却找不到任务执行器?
问题2:如果没有选择,为什么Spring Batch中的线程以“Batch-”开头
即使我使用它而不是任务执行器:
@Bean
public Step step() {
return stepBuilderFactory.get("step")
.<VertragsListe, VertragsListe>chunk(10)
.reader(itemReader())
.processor(itemProcessor())
.writer(itemWriter())
.taskExecutor(new SimpleAsyncTaskExecutor())
.build();
}
我仍然收到“找不到任务执行器”。
我认为它与 WriterExecutor 有关,尝试使用上下文处理器调试 API,对我有用