rap*_*apt 4 java spring multithreading spring-mvc spring-batch
我有一个Spring-Batch作业,我从Spring MVC控制器启动.控制器从用户获取上载文件,作业应该处理文件:
@RequestMapping(value = "/upload")
public ModelAndView uploadInventory(UploadFile uploadFile, BindingResult bindingResult) {
// code for saving the uploaded file to disk goes here...
// now I want to launch the job of reading the file line by line and saving it to the database,
// but I want to launch this job in a new thread, not in the HTTP request thread,
// since I so not want the user to wait until the job ends.
jobLauncher.run(
jobRegistry.getJob(JOB_NAME),
new JobParametersBuilder().addString("targetDirectory", folderPath).addString("targetFile", fileName).toJobParameters()
);
return mav;
}
Run Code Online (Sandbox Code Playgroud)
我尝试过以下XML配置:
<job id="writeProductsJob" xmlns="http://www.springframework.org/schema/batch">
<step id="readWrite">
<tasklet task-executor="taskExecutor">
<chunk reader="productItemReader" writer="productItemWriter" commit-interval="10" />
</tasklet>
</step>
</job>
<bean id="taskExecutor"
class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<property name="corePoolSize" value="5" />
<property name="maxPoolSize" value="5" />
</bean>
Run Code Online (Sandbox Code Playgroud)
...但似乎多线程仅在作业边界内发生.即,控制器线程等待直到作业结束,并且作业执行由多个线程处理(这很好但不是我想要的主要内容).我想要的主要是作业将在一个单独的线程(或线程)上启动,而控制器线程将继续执行而不等待作业线程结束.
有没有办法用Spring-batch实现这个目标?
官方文档描述了您的确切问题以及4.5.2中的解决方案.从Web容器中运行作业:
[...]控制器使用
JobLauncher已配置为异步启动的作业启动作业,该作业立即返回JobExecution.Job可能仍在运行,但是,这种非阻塞行为允许控制器立即返回,这在处理HttpRequest时是必需的.
所以你在尝试使用时非常接近TaskExecutor,但是需要传递给它JobLauncher:
<bean id="jobLauncher"
class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
<property name="jobRepository" ref="jobRepository" />
<property name="taskExecutor" ref="taskExecutor"/>
</bean>
Run Code Online (Sandbox Code Playgroud)
免责声明:我从未使用过Spring Batch ...
| 归档时间: |
|
| 查看次数: |
10135 次 |
| 最近记录: |