java—如何为特定进程指定线程池

zpf6vheq  于 2021-07-23  发布在  Java
关注(0)|答案(1)|浏览(290)

我的配置实现了asyncconfigurer,如下所示:

@Configuration
@EnableAsync
public class AsyncConfiguration implements AsyncConfigurer {

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setMaxPoolSize(5);
        executor.setCorePoolSize(5);
        executor.setQueueCapacity(500);
        executor.initialize();
        return executor;
    }

新的线程池在以下情况下运行良好:

@Component
public class MessageJmsListener {

    @Async
    @EventListener
    public void onApplicationEvent(CustomMessage messageJmsWrapper) {
        log.info("Current thread: {}", Thread.currentThread().getName());
    }

    @Async
    @EventListener
    public void onApplicationEventSecond(SecondCustomMessage messageJmsWrapper) {
        log.info("Second Listener thread: {} , Thread.currentThread().getName());
    }
}

我希望实现这样一种效果,即对于第一个侦听器,我给出一个单独的bean(线程数),对于第二个侦听器,我给出一个单独的bean。这样的事可能吗?
提前谢谢!致以最诚挚的问候

epggiuax

epggiuax1#

看起来使用限定符可以帮助您。创建两个不同的执行器,并为每个执行器添加不同的限定符。第一个用于一个参数集的第一个侦听器,第二个用于另一个参数集不同的侦听器。参见本线程中的示例。
本例中的另一种方法是,通过在调用它的注解中添加executor name来调用正确的executor。例子:

@Configuration
@EnableAsync
class ApplicationAsyncConfiguration {

    @Bean(name = "maxThreadingExecutor")
    public Executor maxThreadingExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setMaxPoolSize(5);
        executor.setCorePoolSize(5);
        executor.setQueueCapacity(500);
        executor.initialize();
        return executor;
    }

    @Bean(name = "defaultExecutor")
    public Executor defaultExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setMaxPoolSize(2);
        executor.setCorePoolSize(2);
        executor.setQueueCapacity(500);
        executor.initialize();
        return executor;
    }

}
@Component
public class MessageJmsListener {

    @Async("maxThreadingExecutor")
    @EventListener
    public void onApplicationEvent(CustomMessage messageJmsWrapper) {
        log.info("Current thread: {}", Thread.currentThread().getName());
    }

    @Async("defaultExecutor")
    @EventListener
    public void onApplicationEventSecond(SecondCustomMessage messageJmsWrapper) {
        log.info("Second Listener thread: {}", Thread.currentThread().getName());
    }

}

在这个答案中看到更多,可能会有所帮助。

相关问题