java - 如何使 Async 注解在 Spring Boot 中工作?

标签 java spring spring-boot

我创建了一个简单的 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/

相关文章:

java - 检索作为子文档的数组元素中符合条件的所有文档

java - ArrayList 通过调用的方法进行操作

spring - Spring Boot Cloud Foundry 报错 No unique service maching interface 报错

java - 来自根路径的 Zuul 路由

java - 页面请求未应用于结果

java - 需要澄清 Java 中监听器匿名类的概念

java - JPanel "paintComponent"没有 JLabel 就无法调用

java - Spring getJdbcTemplate().update 插入动态对象

java - 在签名中没有 RedirectAttributes 的情况下访问方法中的 RedirectAttributes

java - 尝试定义自定义 PropertyMap 时出现 NullPointerException