如何在Spring Boot中使Aysnc注释起作用?

问题描述 投票:0回答:2

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

    @Scheduled(fixedRateString = "${config.scheduleInterval}")
    public void pollDataWithFixSchedule() {
        asyncCall();
    }

    @Async()
    public void asyncCall(){
       System.out.printly("Current thread -- {}",Thread.currentThread().getName())
)
    }
    @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);
    }
}
java spring spring-boot
2个回答
2
投票

在您的配置类中,您必须添加@EnableAsync批注

此处的示例:

@Configuration
@EnableAsync
public class AsynchConfiguration
{
    @Bean(name = "asyncExecutor")
    public Executor asyncExecutor()
    {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(3);
        executor.setMaxPoolSize(3);
        executor.setQueueCapacity(100);
        executor.setThreadNamePrefix("AsynchThread-");
        executor.initialize();
        return executor;
    }
}

© www.soinside.com 2019 - 2024. All rights reserved.