代码之家  ›  专栏  ›  技术社区  ›  brain storm

@Scheduled和@Async在spring boot中共享相同的线程池

  •  6
  • brain storm  · 技术社区  · 8 年前

    我配置了两个不同的线程池,一个用于 @Scheduled 和其他 @Async . 但是,我注意到 @异步 未使用。

    以下是计划程序配置

    @Configuration
    @EnableScheduling
    public class SchedulerConfig implements SchedulingConfigurer {
        private final int POOL_SIZE = 10;
    
        @Override
        public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
            ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
            threadPoolTaskScheduler.setPoolSize(POOL_SIZE);
            threadPoolTaskScheduler.setThreadNamePrefix("my-sched-pool-");
            threadPoolTaskScheduler.initialize();
            scheduledTaskRegistrar.setTaskScheduler(threadPoolTaskScheduler);
        }
    }
    

    以下是异步的配置

    @Configuration
    @EnableAsync
    public class AppConfig {
    
     @Bean(name = "asyncTaskExecutor")
        public TaskExecutor asyncExecutor() {
            ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
            executor.setCorePoolSize(15);
            executor.setMaxPoolSize(15);
            executor.setQueueCapacity(100);
            executor.setThreadNamePrefix("my-async-pool-");
            executor.initialize();
            return executor;
        }
    }
    

    下面是我调用它们的方式

    @Scheduled(fixedRateString = "2000" )
        public void schedule() {
          log.debug("here is the message from schedule");
          asyncMethod();
        }
    
    @Async("asyncTaskExecutor")
    public void asyncMethod(){
      log.info("here is the message from async");
    }
    

    这是日志

    {"thread":"my-sched-pool-1","level":"DEBUG","description":"here is the message from schedule"}
    {"thread":"my-sched-pool-1","level":"INFO","description":"here is the message from async"}
    

    正如您所注意到的,两个日志都有相同的调度程序池。但我希望看到第二个来自async

    1 回复  |  直到 8 年前
        1
  •  10
  •   Pedro    8 年前

    如果你打电话 @Async 相同的方法 class 它们声明您实际上绕过了Spring的代理机制,这就是为什么您的示例不起作用的原因。尝试从单独的 注释为 @Service 或任何其他 @Component 类型。

    @Service
    SomeScheduledClass {
    
      private final SomeAsyncClass someAsyncClass;
    
      public SomeScheduledClass(SomeAsyncClass someAsyncClass) {
        this.someAsyncClass = someAsyncClass;
      }
    
      @Scheduled(fixedRateString = "2000" )
      public void schedule() {
        log.debug("here is the message from schedule");
        someAsyncClass.asyncMethod();
      }
    }
    
    @Service
    SomeAsyncClass {
      @Async("asyncTaskExecutor")
      public void asyncMethod(){
        log.info("here is the message from async");
      }
    }
    
    推荐文章