Spring Boot 异步任务 @EnableAsync 和 @Async

强大的 spring boot 已经帮忙封装了线程池执行异步任务。再也不用自己写线程池了。

 

以前如果需要执行异步任务,需要自己封装一个线程池,然后吧任务提交到线程池执行。

在 spring boot 中已经封装了改工具,只需要直接启用就可以了。

1、在启动类上增加  @EnableAsync  注解,开启异步任务。

2、在需要异步执行的方法上增加  @Async 注解,标识为一个异步任务。这里需要注意的是,这个异步方法如果在本类中使用 this 调用,则不能达到异步的目的,

例如:

@SpringBootApplication
@ServletComponentScan
@ImportResource("classpath:spring-all.xml")
@EnableTransactionManagement
@EnableScheduling
@EnableAsync
public class DingdingServiceApplication extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(DingdingServiceApplication.class);
    }

    public static void main(String[] args) {
        SpringApplication.run(DingdingServiceApplication.class, args);
    }

}


// 在需要使用的地方

@Service
public class AsyncTest {


    // 注意 异步方法不要有返回值
    @Async
    public void test1(){
            
        // do something

        this.test2(); // 这样调用则不是异步执行

    }


    @Async
    public void test2(){
        // do something
    }
}

更多JAVA 问题,请关注微信小程序:

猜你喜欢

转载自blog.csdn.net/wab719591157/article/details/88534885