我创建了一个简单的 Spring Boot 应用程序,其中包含计划 (@Scheduled
) 任务。在该计划任务中,我想使用 @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);
}
}
最佳答案
根据Baeldung :
@Async has two limitations:
- it must be applied to public methods only
- self-invocation – calling the async method from within the same class – won't work
The reasons are simple – the method needs to be public so that it can be proxied. And self-invocation doesn't work because it bypasses the proxy and calls the underlying method directly. so you can put your async method in a service and use it from there
关于java - 如何使 Async 注解在 Spring Boot 中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58622413/