我在两个课程上使用 Spring
@Async
。两者最终都是实现一个接口。我正在创建两个单独的 ThreadPoolTaskExecutor
,因此每个类都有自己的线程池可供使用。
但是,因为我想到了代理以及 Spring 如何实现 Async 类,所以我必须将
@Async
注解放在基本接口上。因此,两个类最终都使用相同的 ThreadPoolTaskExecutor
。
是否可以告诉Spring对于这个Bean(在本例中我将实现该接口的类称为Service),使用这个
ThreadPoolTaskExecutor
?
默认情况下,在方法上指定
@Async
时,将使用的执行器是提供给“注释驱动”元素的执行器,如此处所述。
但是,当需要指示在执行给定方法时应使用默认执行器以外的执行器时,可以使用
@Async
注释的 value 属性。
@Async("otherExecutor")
void doSomething(String s) {
// this will be executed asynchronously by "otherExecutor"
}
在这种情况下,“otherExecutor”可以是 Spring 容器中任何 Executor bean 的名称,也可以是与任何 Executor 关联的限定符的名称,例如使用元素或 Spring 的
@Qualifier
注释 指定
https://docs.spring.io/spring/docs/current/spring-framework-reference/html/scheduling.html
并且您可能需要在应用程序中使用您希望的池设置指定 otherExecutor bean。
@Bean
public TaskExecutor otherExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
executor.setMaxPoolSize(10);
executor.setQueueCapacity(25);
return executor;
}