Spring Boot 3.2 启用虚拟线程后 ThreadPoolTaskScheduler 报错
Spring Boot 虚拟线程 About 2,379 words错误信息
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of method rateLimiter in z.note.lite.web.interceptor.RateLimiterConfig required a bean of type 'org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler' that could not be found.
The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler' in your configuration.
原始配置
@Configuration(proxyBeanMethods = false)
@EnableScheduling
public class TaskConfig {
@Bean
@ConditionalOnBean
public ThreadPoolTaskScheduler threadPoolTaskScheduler(ThreadPoolTaskScheduler threadPoolTaskScheduler) {
return threadPoolTaskScheduler;
}
}
原因
开启虚拟线程后,Spring Boot 3.2
自动注入的Bean
,根据条件注入了SimpleAsyncTaskScheduler
,没有注入ThreadPoolTaskScheduler
。
替代方案
在开启了虚拟线程后,可以选择注入TaskScheduler
。
@Bean
public RateLimiter rateLimiter(TaskScheduler taskScheduler) {
return new JdkRateLimiter(taskScheduler, rateLimiterProperties.getDuration(), rateLimiterProperties.getCount());
}
源码
class TaskSchedulingConfigurations {
@Configuration(proxyBeanMethods = false)
@ConditionalOnBean(name = TaskManagementConfigUtils.SCHEDULED_ANNOTATION_PROCESSOR_BEAN_NAME)
@ConditionalOnMissingBean({ TaskScheduler.class, ScheduledExecutorService.class })
@SuppressWarnings("removal")
static class TaskSchedulerConfiguration {
@Bean(name = "taskScheduler")
@ConditionalOnThreading(Threading.VIRTUAL)
SimpleAsyncTaskScheduler taskSchedulerVirtualThreads(SimpleAsyncTaskSchedulerBuilder builder) {
return builder.build();
}
@Bean
@ConditionalOnThreading(Threading.PLATFORM)
ThreadPoolTaskScheduler taskScheduler(TaskSchedulerBuilder taskSchedulerBuilder,
ObjectProvider<ThreadPoolTaskSchedulerBuilder> threadPoolTaskSchedulerBuilderProvider) {
ThreadPoolTaskSchedulerBuilder threadPoolTaskSchedulerBuilder = threadPoolTaskSchedulerBuilderProvider
.getIfUnique();
if (threadPoolTaskSchedulerBuilder != null) {
return threadPoolTaskSchedulerBuilder.build();
}
return taskSchedulerBuilder.build();
}
}
}
Views: 865 · Posted: 2024-03-19
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb/LiteNote扫描下方二维码关注公众号和小程序↓↓↓
Loading...