0

Async通过实现AsyncConfigurer和覆盖getAsyncExecutor来定义我的Executor. 现在我想公开一个端点,以返回 Async 使用的 Executor 的当前队列大小、线程数等。但是我找不到一种方法来查找或自动连接 Async 使用的当前执行程序。我在想我可以定义一个bean,该getAsyncExecutor方法和我的报告服务都将使用它。但我想知道是否有一种更简单/更合适的方式可以与 async 交互以获取当前的Executor.

我目前的配置:

@Configuration
@EnableAsync
public class AsyncConfiguration implements AsyncConfigurer {

    @Override
    public Executor getAsyncExecutor() {
        final ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();

        threadPoolTaskExecutor.setThreadNamePrefix("async-thread-");
        threadPoolTaskExecutor.setCorePoolSize(2);
        threadPoolTaskExecutor.setMaxPoolSize(2);
        threadPoolTaskExecutor.setQueueCapacity(100);

        threadPoolTaskExecutor.initialize();

        return threadPoolTaskExecutor;
    }
}
4

1 回答 1

1

You haven't registered a bean for the ThreadPoolTaskExector.

@Configuration
@EnableAsync
public class AsyncConfiguration implements AsyncConfigurer {

    @Override
    public Executor getAsyncExecutor() {
        return taskExecutor();
    }

    @Bean
    public ThreadPoolTaskExecutor taskExecutor() {
       ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setThreadNamePrefix("async-thread-");
        threadPoolTaskExecutor.setCorePoolSize(2);
        threadPoolTaskExecutor.setMaxPoolSize(2);
        threadPoolTaskExecutor.setQueueCapacity(100);
        return threadPoolTaskExecutor;
    }
}

However Spring Boot 2.1 already pre-configures a TaskExecutor for you which you can configure through properties. You can then remove all config and only use @EnableAsync in your configuration.

spring.task.execution.pool.core-size=2
spring.task.execution.pool.max-size=2
spring.task.execution.pool.queue-capacity=100
spring.task.exection.thread-name-prefix=async-thread-

This configuration, together with a single @EnableAsync will achieve the same, without additional configuration.

With either configuration, you can now use @Autowired to get the instance in your service.

于 2020-08-13T06:32:38.860 回答