首页 > 解决方案 > 如何使 Aysnc 注释在 Spring Boot 中工作?

问题描述

我创建了一个带有预定 ( @Scheduled) 任务的简单 Spring Boot 应用程序。在那个计划任务中,我想用 调用 async 函数@Async,但我可以看到它仍然在调度线程上运行,而无需切换到另一个线程。我也尝试自定义执行器,但没有运气。这里有一些代码。我也已经在主类中启用了异步

    public class scheduledService {
    @Scheduled(fixedRateString = "${config.scheduleInterval}")
    public void pollDataWithFixSchedule() {
        AsyncService service = new AsyncService();
        service.asyncCall();
        service.asyncCall();
        service.asyncCall();
 asyncCall();
    }
}
    public class AsyncService {
    @Async()
    public void asyncCall(){
       System.out.printly("Current thread -- {}",Thread.currentThread().getName()))
       Thread.sleep(10000);
    }
}
    @Bean(name = "MyThreadPoolExecutor")
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(7);
        executor.setMaxPoolSize(42);
        executor.setQueueCapacity(11);
        executor.setThreadNamePrefix("MyThreadPoolExecutor-");
        executor.initialize();
        return executor;
    }
@SpringBootApplication
@EnableScheduling
@EnableAsync
public class ScheduledApplication {

    public static void main(String[] args) {
        SpringApplication application = new SpringApplication(ScheduledApplication.class);
        application.setBannerMode(Banner.Mode.OFF);
        application.run(args);
    }
}

标签: javaspringspring-boot

解决方案


根据Baeldung

@Async 有两个限制:

  • 它必须仅应用于公共方法
  • 自调用——从同一个类中调用异步方法——不起作用

原因很简单——方法需要公开才能被代理。而自调用也不起作用,因为它绕过了代理,直接调用了底层方法。所以你可以把你的异步方法放在一个服务中并从那里使用它


推荐阅读