java - Spring Boot - @Async 被忽略

标签 java spring multithreading asynchronous spring-boot

使用 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/

相关文章:

java - 添加到 X509Data 的证书列表时 X509Certificates 重复

Java 和 Spring JDBC : How to simulate table in database doesn't exist for testing (without actually dropping or renaming it)

java - Assert.notThrown 可以在抛出异常时指定一条消息

java - executor.invokeAll() 未完成执行

java - 反射(reflect) Spring 应用程序在运行时配置中所做的更改,而无需重建它

Java制作行和列

java - 在Java ExecutorService中如何设置请求消耗的最大线程数

c# - 使用 Tasks (TPL) 库会使应用程序多线程吗?

java - 2D 平台游戏中的碰撞错误

linux - Tesseract-OCR : Using Tess4j in spring mvc web application on linux environment