Spring 异步线程池:
1、配置自定义线程池和启用异步
/** * @author 悟空 * @date 2020/9/3 */ @Configuration @EnableAsync public class AsyncConfig implements AsyncConfigurer { @Override public Executor getAsyncExecutor() { // 定义线程池 ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(); // 核心线程数 taskExecutor.setCorePoolSize(10); // 线程池最大线程数 taskExecutor.setMaxPoolSize(50); // 线程队列最大线程数 taskExecutor.setQueueCapacity(1000); // 初始化 taskExecutor.initialize(); return taskExecutor; } }2、编写异步服务接口
/** * @author 悟空 * @date 2020/9/4 * 异步服务接口 */ public interface AsyncService { /** * 模拟生成报表的异步方法 */ void generateReport(); }3、编写异步服务接口实现类
/** * @author 悟空 * @date 2020/9/4 * 实现异步服务方法 */ @Service public class AsyncServiceImpl implements AsyncService { @Override @Async public void generateReport() { // 打印异步线程名称 out.println("报表线程名称:" + "【"+ Thread.currentThread().getName() +"】"); } }4、实现异步控制器
/** * @author 悟空 * @date 2020/9/4 * 异步控制器 */ @RestController @RequestMapping("/async") public class AsyncController { private final AsyncService asyncService; public AsyncController(AsyncService asyncService) { this.asyncService = asyncService; } @GetMapping("/page") public String asyncPage() { System.out.println("请求线程名称:" + "【"+ Thread.currentThread().getName() +"】"); // 异步调用服务 asyncService.generateReport(); return "async"; } }5、结果展示