Nacos+@RefreshScope使用场景
线程池配置动态刷新
yaml配置
- 此配置在Nacos配置中心
spring:
task:
execution:
pool:
core-size: 30
max-size: 100
queue-capacity: 0
thread-name-prefix: async-task-
java配置类
- @RefreshScope放在@Bean这里,如果放在Class上面无效
@Configuration
@EnableAsync
public class TaskExecutionConfig {
@Bean
@RefreshScope
public ThreadPoolTaskExecutor asyncExecutor(TaskExecutionProperties springTaskExecutorProperties) {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(springTaskExecutorProperties.getPool().getCoreSize());
executor.setMaxPoolSize(springTaskExecutorProperties.getPool().getMaxSize());
executor.setQueueCapacity(springTaskExecutorProperties.getPool().getQueueCapacity());
// rejection-policy:当pool已经达到max size的时候,如何处理新任务
// CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
executor.initialize();
return executor;
}
}
Nacos配置中心修改配置,ThreadPoolTaskExecutor会重新加载实例化一个Bean