1. spring框架中使用异步线程池;
2. 使用场景,比较耗时的操作,如数据统计,报表生成,可以使用多个线程进行处理,需要及时响应的处在一个线程,及时完成请求;耗时的延时操作,可以另开启一个线程进行执行,避免等待阻塞。
3. 涉及的接口及类及注解:
AsyncConfigurer: 配置异步线程池的接口;
ThreadPoolTaskExecutor:线程池;
@EnableAsync:注解配置文件(@Configuration修饰java文件,并且最好实现AsyncConfigurer接口,并重写 getAsyncExecutor方法);
@Async:注解需要异步线程执行的方法。
4. 实例:
@Configuration
@EnableAsync
public class SpringAsyncConfig implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor taskExecutor=new ThreadPoolTaskExecutor();
taskExecutor.setCorePoolSize(10);
taskExecutor.setMaxPoolSize(30);
taskExecutor.setQueueCapacity(2000);
taskExecutor.initialize();
return taskExecutor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return null;
}
}
@Service
public class AsyncServiceImpl {
@Async
public void generateReport(){
System.out.println("报表线程名称:"+"["+Thread.currentThread().getName()+"]");
}
}
@RestController @RequestMapping("/async") public class AsyncController { @Autowired private AsyncServiceImpl asyncServiceImpl; @RequestMapping("/page") public String asyncPage(){ System.out.println("报表线程名称:"+"["+Thread.currentThread().getName()+"]"); asyncServiceImpl.generateReport(); return "async"; } }