多个ThreadPoolTask​​执行Spring Java配置

gre*_*fox 3 java spring spring-java-config

我的应用程序中需要多个任务执行器,但我没有看到如何使用Java Config.XML版本很简单,但我必须遗漏Java Config

我需要两个具有不同队列和线程池大小的不同执行程序,如何使用Java Config完成此操作?

这是我的AsyncConfig类

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

@EnableScheduling
@EnableAsync
@Configuration
public class AsyncConfig implements AsyncConfigurer {

    @Autowired
    Environment environment;

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(environment.getRequiredProperty("aysnc.executor.poolSize", Integer.class));
        executor.setMaxPoolSize(environment.getRequiredProperty("aysnc.executor.maxPoolSize", Integer.class));
        executor.setQueueCapacity(environment.getRequiredProperty("aysnc.executor.queueCapacity", Integer.class));
        executor.initialize();
        return executor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new SimpleAsyncUncaughtExceptionHandler();
    }
}
Run Code Online (Sandbox Code Playgroud)

Den*_*ker 7

我认为您可以删除界面,在JavaConfig中标记为2个Executors @Bean(name = "nameOfExecutor"),然后@Async("nameOfExecutor")根据文档使用bean名称:May be used to determine the target executor to be used when executing this method, matching the qualifier value (or the bean name) of a specific Executor or TaskExecutor bean definition.