我想实现一个异步任务,以及一个立即返回并在后台启动任务的页面。但是,页面会等待后台任务完成,然后才返回。当我访问/start
加载页面需要 15 秒。我正在使用 Spring 3.2.0。我有一行包含 <task:annotation-driven/>
在我的 test-servlet.xml 中。
奇怪的是,即使我将 @Async 替换为 @Async("this_bean_does_not_exist"),应用程序也会执行相同的操作(尽管我希望引用不存在的 bean 时出现异常)。
public interface AsyncTestService {
void startSlowProcess();
}
@Service
public class AsyncTestServiceImpl implements AsyncTestService {
@Override
@Async
public void startSlowProcess() {
try {
Thread.sleep(15000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
@Controller
public class TestController {
@Autowired
AsyncTestService asyncTestService;
@RequestMapping("/start")
@ResponseBody
public String startSlowProcess() {
asyncTestService.startSlowProcess(); // It takes 15s to complete
return "STARTED"; // should return immediately
}
}
最佳答案
您可能需要一个 executor .试试这个:
<task:annotation-driven executor="myExecutor" />
<task:executor id="myExecutor" pool-size="5"/>
编辑:另一种可能的解决方案:使用EnableAsync相反(自 Spring 3.1 起可用)
关于java - Spring MVC 异步任务同步运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15172159/