在开发spring boot应用服务的时候,难免会使用到异步任务及线程池。spring boot的线程池是可以自定义的,所以我们经常会在项目里面看到类似于下面这样的代码
@Bean
public Executor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(config.getCorePoolSize());
executor.setMaxPoolSize(config.getMaxPoolSize());
executor.setQueueCapacity(config.getQueueCapacity());
executor.setThreadNamePrefix("TaskExecutePool-");
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.initialize();
return executor;
}
使用起来很方便,但是这样做有几个问题:
为了解决上述的问题,我开发了一个Spring Boot Starter(开源项目地址:https://gitee.com/hanxt/zimug-monitor-threadpool ),方便集成到Spring Boot项目里面去。目标是:在不改变SpringBoot线程池的核心实现的基础上,使其可视化、易观测、易配置、易使用。
需要说明的是:zimug-monitor-threadpool并未改变SpringBoot线程池的实现,只是在其基础上添加了初始化阶段的配置自动化加载,运行时的状态监控。所以任何有关Spring Boot线程池运行时性能的讨论,都与本文及其实现无关。
通过上文的项目地址获取源码,然后maven编译install本地m2仓库。然后通过下面的maven坐标引入
<dependency>
<groupId>com.zimuggroupId>
<artifactId>zimug-monitor-threadpoolartifactId>
<version>1.0version>
dependency>
如下配置spring boot YAML(application.yml)所示,配置了两个线程池,分别是test、test2。当thread-pool.enable=true的时候线程池配置生效。
thread-pool:
enable: true
poolLists:
- poolId: test #线程池唯一标识
poolName: 测试1 #线程池的中文描述,比如线程池给谁用?
coreSize: 5 #线程池初始化核心线程数量
maxSize: 10 #线程池最大线程容量
queueCapacity: 10 #线程池等待队列的容量
- poolId: test2
poolName: 测试2
coreSize: 5
maxSize: 10
queueCapacity: 10
通过下面的这张图理解上面的配置信息

使用方式和SpringBoot 代码方式自定义线程池的使用方式是一样的。使用@Async注解的值是test,调用该注解标识的函数就会放入上文中配置的test线程池里面去执行。
@Component
public class TestTask {
@Async("test") //注意这里,test是线程池配置的poolId
public Future<String> test() throws Exception {
System.out.println("当前线程:" + Thread.currentThread().getName());
return new AsyncResult<>("测试任务");
}
}
在项目中引入zimug-monitor-threadpool之后,进行线程池配置,使用线程池。访问服务的/pool.html即可获取当前SpringBoot服务的线程池配置信息,以及运行时状态信息。

zimug-monitor-threadpool的实现原理也非常简单,简单说一下原理,具体实现参考源码。
configurableBeanFactory.registerSingleton(pool.getPoolId(), taskExecutor);
ThreadPoolTaskExecutor memThreadPool = (ThreadPoolTaskExecutor) applicationContext.getBean(poolModel.getPoolId());
觉得对您有帮助的话,帮我点赞、分享!您的支持是我不竭的创作动力!。更多精彩内容公众号:字母哥杂谈。