总是调用Spring自定义ThreadPoolTask​​Executor

时间:2019-02-26 12:16:48

标签: java spring spring-boot java.util.concurrent

在特殊情况下,我尝试将Spring上下文复制到Runnable / Callable任务。我希望其他线程能够像以前一样运行。

我已经读过这个How to enable request scope in async task executor

并实现了自定义ThreadPoolTask​​Executor +装饰器。

@Configuration
public class ContextCopyConfig {

    private Integer connectionsLimit=10;

    @Bean(name = "contextExecutor")
    public Executor contextExecutor() {
        ThreadPoolTaskExecutor poolExecutor = new ThreadPoolTaskExecutor();
        poolExecutor.setTaskDecorator(new ContextCopyingDecorator());
        poolExecutor.setMaxPoolSize(connectionsLimit);
        poolExecutor.setCorePoolSize(connectionsLimit);

        poolExecutor.initialize();
        return poolExecutor;
    }

}

我打算如下使用该执行器:

@Autowired
@Qualifier(value = "contextExecutor")
private Executor contextExecutor;

public void parallelHere() throws IOException, InterruptedException, ExecutionException {
    Collection<Callable<Pair<String, OutputStream>>> tasks = new ArrayList<>(); //some tasks

    //ExecutorService executor = Executors.newFixedThreadPool(connectionsLimit); 

    List<Future<Pair<String, OutputStream>>> results = ((ThreadPoolTaskExecutor) contextExecutor).getThreadPoolExecutor().invokeAll(tasks);
    ((ThreadPoolTaskExecutor) contextExecutor).getThreadPoolExecutor().shutdown(); //always reclaim resources
}

但是,contextExecutor总是被调用(在任何线程中!)。 我该如何解决?

1 个答案:

答案 0 :(得分:0)

此帖子:

How to create additional TaskExecutor beside TaskExecutionAutoConfiguration?

描述问题。仅当用户未创建自定义启动器时,Springboot才会创建默认的执行器。 在SpringBoot 2+中,您必须使用

@AutoConfigureAfter(TaskExecutionAutoConfiguration.class)

在您的自定义配置上。

但是,在以前的Spring版本中,不存在TaskExecutionAutoConfiguration,并且工厂执行者是创建的。使用下面的几行,您可以创建由Spring创建的默认执行程序的样例副本。

@Primary
@Bean
//see package org.springframework.aop.interceptor.AsyncExecutionInterceptor
public Executor getDefaultExecutor(){
    //     Executor defaultExecutor = super.getDefaultExecutor(beanFactory);
    //     return (defaultExecutor != null ? defaultExecutor : new SimpleAsyncTaskExecutor());
    return new SimpleAsyncTaskExecutor();
}
相关问题