如何为异步Spring使用多个threadPoolExecutor [英] How to use multiple threadPoolExecutor for Async Spring
问题描述
我在两个类上使用Spring @Async.两者最终都实现了一个接口.我正在创建两个单独的ThreadPoolTaskExecutor,因此每个类都有自己的ThreadPool可以使用.但是由于我对代理有一些想法,以及Spring如何实现Async类,因此必须在基本接口上放置@Async批注.因此,两个类最终都使用相同的ThreadPoolTaskExecutor. 是否可以告诉Spring,对于此Bean(在这种情况下,我将实现该接口的类称为Service),请使用此ThreadPoolTaskExecutor.
I am using Spring @Async on two classes. Both are ultimately implementing an interface. I am creating two separate ThreadPoolTaskExecutor so each class has its own ThreadPool to work off of. However due to I think something with proxy and how Spring implements Async classes, I have to put the @Async annotation on the base interface. Because of this, both classes end up using the same ThreadPoolTaskExecutor. Is it possible to tell Spring that for this Bean (in this case I am calling the classes that implement that interface a Service), use this ThreadPoolTaskExecutor.
推荐答案
默认情况下,在方法上指定@Async
时,将使用的执行程序是提供给注释驱动"元素的执行程序,如此处 .
By default when specifying @Async
on a method, the executor that will be used is the one supplied to the 'annotation-driven' element as described here.
但是,当需要指示在执行给定方法时应使用默认值以外的执行器时,可以使用@Async
批注的value属性.
However, the value attribute of the @Async
annotation can be used when needing to indicate that an executor other than the default should be used when executing a given method.
@Async("otherExecutor")
void doSomething(String s) {
// this will be executed asynchronously by "otherExecutor"
}
在这种情况下,"otherExecutor"可以是Spring容器中任何Executor bean的名称,也可以是与任何Executor关联的限定符的名称,例如根据元素或Spring的@Qualifier
注释
In this case, "otherExecutor" may be the name of any Executor bean in the Spring container, or may be the name of a qualifier associated with any Executor, e.g. as specified with the element or Spring’s @Qualifier
annotation
https://docs.spring. io/spring/docs/current/spring-framework-reference/html/scheduling.html
可能您需要使用所需的池设置在应用程序中指定otherExecutor bean.
And probably you need to specify the otherExecutor bean in you app with the pool settings you wish.
@Bean
public TaskExecutor otherExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
executor.setMaxPoolSize(10);
executor.setQueueCapacity(25);
return executor;
}
这篇关于如何为异步Spring使用多个threadPoolExecutor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!