使用 Spring Boot 1.5.2.RELEASE
和 @Async
注释似乎被忽略了。
环境设置如下:
@SpringBootApplication
@EnableAsync
public class Application extends AsyncConfigurerSupport {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(2);
executor.setMaxPoolSize(2);
executor.setQueueCapacity(500);
executor.setThreadNamePrefix("async-task-");
executor.initialize();
return executor;
}
...
...异步方法本身:
@Service
public class MyService {
@Async
public Future<Long> asyncTask() throws Exception {
Long test = 1023L;
Thread.sleep(10000);
return new AsyncResult<>(test);
}
}
...现在我正在尝试使用它:
@RestController
public MyController {
@Autowired
public MyService myService;
@PostMapping("/test")
public ResponseEntity<MyResponse> test() {
return new ResponseEntity<>(
new MyResponse(myService
.asyncTask()
.get()),
HttpStatus.OK);
}
}
...并且 Controller 方法仍然挂起 10sec
而不是立即返回。
@Async
方法从不同的对象调用。正如它在类似问题中提到的那样,它既不是私有(private)的也不是交易的。
如何让方法异步调用?
最佳答案
你应该看看 Future#get javadoc :
Waits if necessary for the computation to complete, and then retrieves its result.
您正在通过调用 get
方法将异步方法转换为同步调用。
因此,不是调用 get
,而是返回 Future
。 Spring MVC 支持 future as return type :
A ListenableFuture or CompletableFuture/CompletionStage can be returned when the application wants to produce the value from a thread pool submission.
例子:
return myService.asyncTask().thenApply(r -> ResponseEntity.ok(new MyResponse(r)));
关于java - Spring Boot - @Async 被忽略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43162216/