只須要建立一個 Java 配置類, 實現 AsyncConfigurer 接口, 實現 getAsyncExecutor 方法返回線程池. 在 java 配置文件類上加註解 @EnableAsync 開啓異步可用, 而後就能夠在 service 方法上使用註解 @Async 使用異步調用java
1. 建立一個 java 配置類文件.spring
package com.codingos.springboot.test.config; import java.util.concurrent.Executor; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.AsyncConfigurer; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; @Configuration @EnableAsync public class AsyncConfig implements AsyncConfigurer { /** * 定義線程池 */ @Override public Executor getAsyncExecutor() { // 定義線程池 ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(); // 設置核心線程 taskExecutor.setCorePoolSize(10); // 設置最大線程 taskExecutor.setMaxPoolSize(30); // 設置線程隊列最大線程數 taskExecutor.setQueueCapacity(2000); // 初始化 taskExecutor.initialize(); return taskExecutor; } }
2. 建立異步服務 servicespringboot
package com.codingos.springboot.test.service.impl; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; import com.codingos.springboot.test.service.AsyncService; @Service public class AsyncServiceImpl implements AsyncService { @Override @Async // 聲明使用異步調用 public void generateReport() { // 打印當前異步線程名稱 System.out.println("報表線程名稱" + Thread.currentThread().getName()); } }
而後就能夠在 controller 中調用了異步
要注意的是:異步配置文件類上要使用 @EnableAsync 註解,異步 service 的方法上使用 @Async 註解ide