我是Spring批次的新手,无法弄清楚如何做到这一点..
基本上我有一个spring文件轮询器,每隔N分钟运行一次,在某个目录中查找带有某个名字的文件(例如:A.txt& B.txt).在任何时候,此目录中可能有最多2个文件(A和B).通过Spring Batch Job,这两个文件将被处理并持久保存到2个不同的DB表中.
这些文件有些类似,因此使用相同的处理器/写入器.
现在我设置的方式,每个轮询周期1文件被选中并且作业运行.
假设目录中有2个文件(A.txt和B.txt),有没有办法创建2个作业,以便两个作业可以并行运行?
解决方法:
我相信你可以.因为你是春季批次的新手(就像我一样),如果你还没有这样做,我建议你通过the domain language of a batch.
然后,您可以从配置自己的异步JobLauncher开始.例如:
@Bean
public JobLauncher jobLauncher() throws Exception
{
SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
jobLauncher.setJobRepository(jobRepository);
jobLauncher.setTaskExecutor(new SimpleAsyncTaskExecutor());
jobLauncher.afterPropertiesSet();
return jobLauncher;
}
特别注意SimpleAsyncTaskExecutor(作业仓库可以自动装配).此配置将允许下一个可视化的异步执行:
将它与同步执行流程进行比较:
也许它还有助于引用SimpleJobLauncher java doc:
Simple implementation of the JobLauncher interface. The Spring Core
TaskExecutor interface is used to launch a Job. This means that the
type of executor set is very important. If a SyncTaskExecutor is used,
then the job will be processed within the same thread that called the
launcher. Care should be taken to ensure any users of this class
understand fully whether or not the implementation of TaskExecutor
used will start tasks synchronously or asynchronously. The default
setting uses a synchronous task executor.
更多细节和配置选项 – here.
最后,只需创建具有不同名称的作业和/或使用不同的参数集启动它们.天真的例子是:
@Autowired
public JobBuilderFactory jobBuilderFactory;
public Job createJobA() {
return jobBuilderFactory.get("A.txt")
.incrementer(new RunIdIncrementer())
.flow(step1())
.next(step2())
.end()
.build();
}
public Job createJobB() {
return jobBuilderFactory.get("B.txt")
.incrementer(new RunIdIncrementer())
.flow(step1())
.next(step2())
.end()
.build();
}
使用异步作业启动程序执行这些作业将创建两个并行执行的作业实例.这只是一个选项,可能适用于您的上下文,也可能不适用.