概要
开发要点:
- 实现AsyncConfigurer接口
- @EnableAsync开启异步
- @Async标注希望异步执行的方法
1.异步线程池配置类
通过实现AsyncConfigurer接口配置线程池。
@EnableAsync开启异步。
import java.util.concurrent.Executor;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
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 // 开启spring异步
public class AsyncThreadPoolConfig implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor() {
// 定义线程池
ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
// 核心线程数=启用线程的个数
threadPoolTaskExecutor.setCorePoolSize(10);
// 线程池最大线程数
threadPoolTaskExecutor.setMaxPoolSize(300);
// 线程队列最大线程数
threadPoolTaskExecutor.setQueueCapacity(2000);
// 初始化线程池
threadPoolTaskExecutor.initialize();
return threadPoolTaskExecutor;
}
// 异常处理方法
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
System.out.println("异常了......");
return null;
}
}
2.异步方法
@Async标注的方法被调用将使用异步线程池来执行。
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class AsyncServiceImpl{
@Async // 使用异步调用
public String asynctest(String threadName) {
System.out.println(threadName+ " —> " + Thread.currentThread().getName());
return null;
}
}
3.测试
多次调用异步方法。
@Controller
@RequestMapping(path="/asyncmvc")
public class AsyncController {
@Autowired
private AsyncServiceImpl asyncService;
@RequestMapping(value="/ma1")
public String am1(ModelAndView mav){
int num = 1;
while (num <= 15) {
asyncService.asynctest(Thread.currentThread().getName()+ "");
num++;
}
return "asyncmvc/ma1";
}
}
请求http://localhost:8081/asyncmvc/ma1,输出日志:
http-nio-8081-exec-4 —> ThreadPoolTaskExecutor-1
http-nio-8081-exec-4 —> ThreadPoolTaskExecutor-5
http-nio-8081-exec-4 —> ThreadPoolTaskExecutor-9
http-nio-8081-exec-4 —> ThreadPoolTaskExecutor-2
http-nio-8081-exec-4 —> ThreadPoolTaskExecutor-10
http-nio-8081-exec-4 —> ThreadPoolTaskExecutor-8
http-nio-8081-exec-4 —> ThreadPoolTaskExecutor-4
http-nio-8081-exec-4 —> ThreadPoolTaskExecutor-3
http-nio-8081-exec-4 —> ThreadPoolTaskExecutor-6
http-nio-8081-exec-4 —> ThreadPoolTaskExecutor-7
可见,同一线程调用,异步方法使用不同的线程来执行。
github:https://github.com/zhangyangfei/SpringBootLearn.git中的springTech工程。