只须要建立一个 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