springboot中使用异步调用(线程池)

使用场景: 发送短信 发送邮件 App消息推送 节省运维凌晨发布任务时间提供效率

项目地址:https://github.com/heng1234/springboot2.x/tree/master/boot_async

开启异步

首先得在Spring Boot入口类上加上@EnableAsync注解

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;

@SpringBootApplication
@EnableAsync//开启异步
public class BootAsyncApplication {

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

}

自定义异步线程池

默认情况下的异步线程池配置使得线程不能被重用,每次调用异步方法都会新建一个线程,我们可以自己定义异步线程池来优化

AsyncPoolConfig

@Async 注解上指定线程池Bean名称

controller测试

访问 http://localhost:7009/tasks/test1

image-20191107165647272
image-20191107165606065

下一章:springboot中配置定时任务(cron表达式)线程池方式

Last updated

Was this helpful?