我的 Spring Boot 应用程序中有以下配置:
@Configuration
@EnableAsync
@Slf4j
public class AsyncConfig {
private static final int BUFFER = 1024;
@Bean
public AsyncTaskExecutor singleThreadAsyncTaskExecutor(Environment env) {
RingBufferAsyncTaskExecutor rbAsyncExecutor = new RingBufferAsyncTaskExecutor(env);
rbAsyncExecutor.setName("rb-executor");
rbAsyncExecutor.setBacklog(BUFFER);
rbAsyncExecutor.setProducerType(ProducerType.SINGLE);
rbAsyncExecutor.setWaitStrategy(new YieldingWaitStrategy());
log.info("Async task executor loaded");
return rbAsyncExecutor;
}
}
当我运行它时,CPU 使用率达到 100%(有时是 100 左右):
用 visualvm 调查,我看到了这个
但是,当我删除 AsyncTaskExecutor
的实例化时,CPU 使用率变为 0.4%,而 visualvm 显示 CPU 使用率仅为 1%。
我在用 docker 部署它时发现了这个问题,我看到我的主机使用率达到了天花板。
我尝试将缓冲区大小(它是 2048)降低到 1024,但没有任何改变。
没有这个 bean,我的 @Async
服务就不能异步工作。 (未找到用于异步处理的 TaskExecutor bean
)
最佳答案
我想我解决了。
我做的是使用ThreadPoolTaskExecutor
代替RingBuffer,如下
@Bean
public AsyncTaskExecutor getAsync(){
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(7);
executor.setMaxPoolSize(42);
executor.setQueueCapacity(11);
executor.setThreadNamePrefix("AsyncExec-");
executor.initialize();
return executor;
}
出于某种原因,ThreadPoolTaskExecutor
比其他的更轻。
我从 spring framework doc 得到这个
关于java - 配置 AsyncTaskExecutor 时,spring boot 应用程序消耗所有 cpu,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39387036/