Spring 线程池定时监控

在上一篇Spring异步线程池: https://blog.csdn.net/timchen525/article/details/80672186 ,该文介绍了如何使用Spring的注解来配置异步线程操作。
本篇博文中,补充介绍如何通过Spring定时任务来配置定时检测线程池的使用情况。

ThreadPoolExecutor线程池提供了如下几个方法:
getTaskCount():线程池已执行和未执行的任务总数
getCompletedTaskCount():已完成的任务数量
getPoolSize():线程池当前的线程数量
getActiveCount():当前线程池中正在执行任务的线程数量
getQueue().size():获取队列中的任务数

(1)写一个存储线程池的静态字段相关的类:
public abstract class ThreadPoolInfoUtil {   
    public static ConcurrentHashMap<String, ThreadPoolTaskExecutor> threadPoolMap = new ConcurrentHashMap<>();
}
(2)在创建每个线程池时,把线程池实例传入上述的静态字段
@EnableAsync
@Configuration
public class PayThreadPoolConfig {
    
    @Value("${pay.threadNamePrefix}")
    private String threadNamePrefix;
    
    @Value("${pay.maxPoolSize}")
    private Integer maxPoolSize;
    
    @Value("${pay.corePoolSize}")
    private Integer corePoolSize;
    
    @Value("${pay.queueCapacity}")
    private Integer queueCapacity;

    @Bean(value = "paymentTaskExexutor")
    public AsyncTaskExecutor paymentTaskExexutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setThreadNamePrefix(threadNamePrefix);
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();

        ThreadPoolInfoUtil.threadPoolMap.put("paymentTaskExexutor", executor);
        return executor;
    }
}
(3)每隔1分钟打印一次线程池相关的信息
Slf4j
@Component
@EnableScheduling
public class ScheduleService {
    
    @Scheduled(fixedRate = 60000)  // 每隔一分钟打印一次
    public void scheduledFixedRate() {
        ThreadPoolTaskExecutor paymentTaskExexutor = ThreadPoolInfoUtil.threadPoolMap.get("paymentTaskExexutor");
        ThreadPoolExecutor threadPoolExecutor = paymentTaskExexutor.getThreadPoolExecutor();
        String threadNamePrefix = paymentTaskExexutor.getThreadNamePrefix();
        long taskCount = threadPoolExecutor.getTaskCount();
        long poolSize = threadPoolExecutor.getPoolSize();
        long completedTaskCount = threadPoolExecutor.getCompletedTaskCount();
        long activeCount = threadPoolExecutor.getActiveCount();
        long queueSize = threadPoolExecutor.getQueue().size();
        log.info("threadNamePrefix=>{}, taskCount=>{}, completedTaskCount=>{}, activeCount=>{}, queueSize=>{}", 
                threadNamePrefix, taskCount, completedTaskCount, activeCount, queueSize);
    }
}


猜你喜欢

转载自blog.csdn.net/timchen525/article/details/80978111