已在事务中时启动弹簧批处理作业 [英] Start a spring batch job when already within a transaction
问题描述
我有一个简单的 Spring-Service,它(以及其他任务)使用以下代码启动一个 Spring 批处理作业:
I have simple Spring-Service that (among other tasks) starts a spring batch job with the following code:
@Autowired
private JobRegistry jobRegistry;
@Autowired
private JobLauncher jobLauncher;
public void startMyJob() {
Job job = jobRegistry.getJob("myJobName");
JobParameters jobParameters = new JobParametersBuilder().toJobParameters();
jobLauncher.run(job, jobParameters);
}
只要在调用 Serivce-Method 时没有活动的事务,就可以正常工作.但是,对于活动事务,我收到此异常:
This works fine, as long as there is no transaction active when the Serivce-Method is called. However, with an active transaction, I get this exception:
Caused by: java.lang.IllegalStateException: Existing transaction detected in JobRepository. Please fix this and try again (e.g. remove @Transactional annotations from client).
我无法轻易删除现有事务,因为它是由于某些框架代码无法实现而隐含的.
I cannot easily remove the existing transaction, since it is implied due to some framework code that is not within my reach.
那么,在这种情况下,我怎样才能开始这项工作?新作业不应使用现有事务.它可以只是开始自己的事务 - 但如何配置它以使其工作?
So, how can I start the job anyway within this context? The new job just should not use the existing transaction. It could just start its own transaction - but how to configure it to make it work?
推荐答案
使用 AbstractJobRepositoryFactoryBean.ValidateTransactionState
,但要小心使用(警告:龙在前面).
Use AbstractJobRepositoryFactoryBean.ValidateTransactionState
, but use carefully (Warning: Dragons ahead).
要使用另一个事务,您可以注入一个自定义的 SimpleJobLauncher.executor
方法 Executor.run
标记为 @Transactional() (或创建一个自定义的 JobLauncher
并对方法 run
执行相同的技巧.
To use another transaction you can inject a custom SimpleJobLauncher.executor
with method Executor.run
marked as @Transactional() (or create a custom JobLauncher
and do the same trick on method run
).
我还没有尝试过,因为我还没有遇到过这个问题,但希望能帮到你.
I haven't tried because I haven't faced the problem, but hope can help.
这篇关于已在事务中时启动弹簧批处理作业的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!