首页 > 解决方案 > Async 方法的行为不是异步的

问题描述

我写的方法比我想要的要花更多的时间。它依赖于外部系统的响应,所以它很慢。我对此没有太多控制权。由于该方法我不能等待那段时间,所以我的要求是在我初始化该方法并提供所需的参数后,它应该在后台运行,而调用这个耗时方法的父方法将完成它的执行。

我使用了spring的@Async注解将该方法声明为异步的。这个特定的方法是从 RestController 调用的,它将在这个异步方法完成它的执行之前完成它的执行。我已经声明了自定义执行器并将其映射到 dispatcher-servlet.xml 中。

该方法正在异步执行,但是当调用者方法完成它的执行时,即使异步方法仍然不完整,也会突然停止执行。如何实现异步方法完成它的执行,即使调用者方法更早完成。我不能在调用者方法中等待异步方法完成它的执行。

代码示例 @Service 类 TimeConsumingService{

@Async("customExecutor")
    public  void  callTimeConsumingService( ){

//This call takes time between 50000 miliseconds to 70000 miliseconds
} 

}

//Caller Method

@RestController
@RequestMapping("rest/document/content")
public class CallerController
{

@Autowired
TimeConsumingService timeConsumingService;


 @LoggingAdvice
    @RequestMapping(value="/request", method = RequestMethod.POST )
    public String requestContent( @RequestParam(value = "file") MultipartFile file) throws Exception, IOException
    {

timeConsumingService.callTimeConsumingService();

}
}

标签: javaasynchronous

解决方案


推荐阅读