1.为什么要使用异步调用
开发SpringBoot项目中,很多逻辑不需要同步的进行。比如电商订单逻辑中下单后的送积分、物流同步逻辑,尤其是秒杀过程中,只需要满足下单的操作成功就得返回,送积分和物流逻辑不需要在返回之前同步的执行。
2.如何开启异步调用
在方法上使用@Async
在配置类上使用@EnableAsync
即可实现异步调用。
3.异步调用使用自定义线程池
使用
@Async
注解,在默认情况下用的是SimpleAsyncTaskExecutor
线程池,该线程池不是真正意义上的线程池。
使用此线程池无法实现线程重用,每次调用都会新建一条线程。若系统中不断的创建线程,最终会导致系统占用内存过高,引发OutOfMemoryError
错误。
所以我们在使用Spring中的@Async异步框架时一定要自定义线程池,替代默认的SimpleAsyncTaskExecutor。
4.实现
启动类
@EnableAsync
@SpringBootApplication
public class App {
@Bean(name = "asyncPoolTaskExecutor")
public ThreadPoolExecutor executor() {
ThreadPoolExecutor threadPoolExecutor =
new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
return threadPoolExecutor;
}
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
业务类
@RestController
public class TestController {
@Async("asyncPoolTaskExecutor")
@GetMapping("test1")
public String test1() throws InterruptedException {
System.out.println(Thread.currentThread().getName());
Thread.sleep(20 * 1000);
System.out.println("正文");
return "hello";
}
}