java - 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();
}
}
解决方案
推荐阅读
- javascript - 可点击 div 内的模板文字内的链接不起作用(似乎我无法阻止页面重新加载
- html - 类型“数字”不可分配给类型“字符串”.ts(2322)
- javascript - ajax加载时的jQuery点击事件
- javascript - 获取图片中工作表的链接
- php - 在 Laravel 中建立一种 BelongsToThrough 关系
- sql - 使用 SQL 查询从多个表中查找匹配记录
- elasticsearch - Elasticsearch 文档中的某些字段以 @ 和 _ 开头以及一些重复的目的是什么
- php - Mysql - 如果行存在更新,如果不插入
- react-native - react-native 应用程序在不同的 cpu 架构中组装时表现不同
- javascript - RXJS,向嵌套的 observable 添加新的 key:value