@async 在 Spring Boot 中无法按预期工作

问题描述 投票:0回答:1

我正在尝试进行并行休息通话。

我已经在类本身中设置了这样的执行器。

ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(5);
        executor.setMaxPoolSize(25);
        executor.setQueueCapacity(100);
        executor.initialize();
        executor.setThreadNamePrefix("Async-");

我已经将它传递到我完整的未来中,就像这样。

List<CompletableFuture<String>> futures = urls.stream()
                .map( url -> CompletableFuture.supplyAsync(() -> function(url,start), executor))
                .toList();

这按预期工作。 expected

现在,当我尝试使用 @async 注释时,它无法按预期工作,我没有执行程序对象来通过异步调用传递它,因此它不使用我的执行程序。我是 springboot 的新手,所以我不确定 bean 到底是如何工作的。

List<CompletableFuture<String>> futures = urls.stream()
                .map( url -> CompletableFuture.supplyAsync(() -> function(url,start)))
                .toList();

这是我的异步配置文件

@Configuration
@EnableAsync
public class AsyncConfiguration  {
    @Bean
    public Executor asyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(5);
        executor.setMaxPoolSize(25);
        executor.setQueueCapacity(100);
        executor.initialize();
        executor.setThreadNamePrefix("Async-");
        return executor;
    }
}


actual output

我该如何解决这个问题?

java spring-boot asynchronous completable-future
1个回答
0
投票

@EnableAsync
应在使用
@Async
的类或
MainApplication
处进行注释。

例如

@Service
@EnableAsync
public class TestService{

  @Async
  public void doAsync() {
    // ...
  }

}
© www.soinside.com 2019 - 2024. All rights reserved.