如何异步调用不同Spring Bean的多个功能

问题描述

我是Spring引导中的Async新手。

我有一个bean A,如下所示:

 class A {
  
   private final B b;
   private final C c;

   ...
   int x = b.f();
   c.g(x);
   ...
 }

在这里,我想异步调用f()g()。我从不同的文章中获得了一些有关如何使@Async工作的想法。但是,作为一个新手,我不明白如何异步调用返回g()的{​​{1}}。

解决方法

这很简单,将@EnableAsync批注添加到配置类或主应用程序类,然后将@Async批注添加到要在单独线程上异步执行的方法。 Springboot将设置一个线程池,使用代理将自动启动一个新线程来处理方法调用。但是,如果您想从方法中返回某些内容,请使用Future。您还可以通过创建如下所示的线程池执行程序bean并在@Async批注中指定它来控制要使用的线程池。

@Configuration
@EnableAsync
class GeneralConfiguration {

    @Bean(name = "asyncTaskExecutor")
    public Executor threadPoolTaskExecutor() {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setCorePoolSize(10);
        threadPoolTaskExecutor.setMaxPoolSize(20);
        threadPoolTaskExecutor.setThreadNamePrefix("ScheduledTaskThread-");
        threadPoolTaskExecutor.initialize();
        return threadPoolTaskExecutor;
    }

}

class B { 
   @Async("asyncTaskExecutor") //ask spring to use your thread pool for this async task.
   public Future<Integer> f() {
     //Do something
     return new AsyncResult<Integer>(1);
   }   
}

class C {

   @Async
   public void g() {
   //Do something
   }
}

根据您的评论,为了等待您将类B方法f的结果提供为类C方法g的输入,然后使用CompletableFuture像这样:

class B { 
   @Async("asyncTaskExecutor") //ask spring to use your thread pool for this async task.
   public CompletableFuture<Integer> f() {
     //Do something
     return CompletableFuture.completedFuture(1);
   }   
}

然后,在调用该方法之后,请执行以下操作:

   ...
   CompletableFuture<Integer> result = b.f();
   CompletableFuture.allOf(result).join(); //add other futures if you want to wait for other calls to complete.
   c.g(result.get());
   ...

很显然,还有其他优化方法可以使用Completable Future。但这取决于您要如何在代码中使用它。我建议阅读完整的未来文档,并找出最适合您的用例的