我想使用spring boot的异步机制,这是我的代码。
@Slf4j
@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {
private static final int MAX_POOL_SIZE = 50;
private static final int CORE_POOL_SIZE = 20;
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setBeanName("taskExecutor");
taskExecutor.setMaxPoolSize(MAX_POOL_SIZE);
taskExecutor.setCorePoolSize(CORE_POOL_SIZE);
taskExecutor.setThreadNamePrefix("async-task-thread-pool");
taskExecutor.setWaitForTasksToCompleteOnShutdown(true);
taskExecutor.setAwaitTerminationSeconds(60 * 10);
taskExecutor.setRejectedExecutionHandler(
(r, executor) -> log.warn("current thread pool is full, reject to invoke."));
taskExecutor.initialize();
return taskExecutor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return (ex, method, params) ->
{
log.error("invoke async method occurs error. method: {}, params: {}",
method.getName(), JSON.toJSONString(params), ex);
throw new RuntimeException();
};
}
}
我在另一个类的方法上添加了 @Async 注释。
@Override
public Future<Result> getResult(String name);
但是当我调用 getResult()
方法时,它报告No bean named 'taskExecutor' available: Nomatching Executor bean find for qualifier 'taskExecutor' - 既没有限定符匹配,也没有bean名称匹配!
。
然后我找到这个页面:https://www.baeldung.com/spring-async 。我遵循此页面的指南 - 删除 Application.class
上的 @EnableAsync
注释并添加到 AsyncConfig.class
。但仍然收到相同的错误消息。似乎 setBeanName()
方法不起作用。难道是我的用法错误?
顺便说一句,我读过EnableAsync
的api文档,它写道
Note: In the above example the {@code ThreadPoolTaskExecutor} is not a fully managed Spring bean. Add the {@code @Bean} annotation to the {@code getAsyncExecutor()} method
if you want a fully managed bean. In such circumstances it is no longer necessary to manually call the {@code executor.initialize()} method as this will be invoked automatically when the bean is initialized.
不是完全托管的 Spring bean
是什么意思? bean 的哪一部分不由 Spring 管理?
最佳答案
向您的 Bean 注释添加名称,例如 @Bean(name="taskExecutor")
。这应该使您的 bean 可以在名称 taskExecutor 下使用。默认情况下,它注册一个名为 methodName 的 bean。请参阅此处引用Spring Bean
关于java - 无法在 Spring Boot 中使用 @Async,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54183189/