1、实战环境
windowns10;
jdk1.8;
springboot 1.5.9.RELEASE;
开发工具:IntelliJ IDEA;
2、实战步骤梳理
本次实战的步骤如下:
创建springboot工程;
创建Service层的接口和实现;
创建controller,开发一个http服务接口,里面会调用service层的服务;
创建线程池的配置;
将Service层的服务异步化,这样每次调用都会都被提交到线程池异步执行;
扩展ThreadPoolTaskExecutor,在提交任务到线程池的时候可以观察到当前线程池的情况;
3 springboot的线程池配置
创建一个配置类ExecutorConfig,用来定义如何创建一个ThreadPoolTaskExecutor,要使用@Configuration和@EnableAsync这两个注解,表示这是个配置类,并且是线程池的配置类,如下所示:
@Configuration
@EnableAsyncpublic classExecutorConfig {private static final Logger logger = LoggerFactory.getLogger(ExecutorConfig.class);
@BeanpublicExecutor asyncServiceExecutor() {
logger.info("start asyncServiceExecutor");
ThreadPoolTaskExecutor executor= newThreadPoolTaskExecutor();//配置核心线程数
executor.setCorePoolSize(5);//配置最大线程数
executor.setMaxPoolSize(5);//配置队列大小
executor.setQueueCapacity(9999);//配置线程池中的线程的名称前缀
executor.setThreadNamePrefix("async-service-");//rejection-policy:当pool已经达到max size的时候,如何处理新任务//CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
executor.setRejectedExecutionHandler(newThreadPoolExecutor.CallerRunsPolicy());//执行初始化
executor.initialize();returnexecutor;
}
}
注意,上面的方法名称为asyncServiceExecutor,稍后马上用到;
4 创建Service层的接口和实现
创建一个service层的接口AsyncService,如下:
public interfaceAsyncService {/*** 执行异步任务*/
voidexecuteAsync();
}
对应的AsyncServ