Loading

Nacos+@RefreshScope使用场景

Nacos+@RefreshScope使用场景

线程池配置动态刷新

Nacos的yaml配置

  • 以下配置对应TaskExecutionProperties,为Spring自带配置类。使用@ConfigurationProperties注解的properties配置类会自动刷新
spring:
  task:
    execution:
      pool:
        core-size: 30
        max-size: 100
        queue-capacity: 0
      thread-name-prefix: async-task-

java配置类

  • @RefreshScope放在@Bean这里,如果放在Class上面无效
  • TaskExecutionProperties需要通过方法参数或者@Autowired的形式都会自动获取新配置
@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

参考

posted @ 2024-06-22 13:24  FynnWang  阅读(42)  评论(0编辑  收藏  举报