@Service public class ThreadPoolMonitor implements InitializingBean { @Resource (name = "consumerExecutor" ) ThreadPoolTaskExecutor consumerExecutor; @Resource ConnectionPool connectionPool; private static final Iterable<Tag> consumerExecutorTAG = Collections.singletonList(Tag.of( "thread.pool.name" , "consumerExecutor" )); private static final Iterable<Tag> okHttpExecutorTAG = Collections.singletonList(Tag.of( "thread.pool.name" , "okHttpExecutor" )); private final ScheduledExecutorService scheduledExecutor = Executors.newSingleThreadScheduledExecutor(); private Runnable monitor = () -> { //这里需要捕获异常,尽管实际上不会产生异常,但是必须预防异常导致调度线程池线程失效的问题 try { Metrics.gauge( "thread.pool.core.size" , consumerExecutorTAG, consumerExecutor, ThreadPoolTaskExecutor::getCorePoolSize); Metrics.gauge( "thread.pool.largest.size" , consumerExecutorTAG, consumerExecutor, e -> e.getThreadPoolExecutor().getLargestPoolSize()); Metrics.gauge( "thread.pool.max.size" , consumerExecutorTAG, consumerExecutor, ThreadPoolTaskExecutor::getMaxPoolSize); Metrics.gauge( "thread.pool.active.size" , consumerExecutorTAG, consumerExecutor, ThreadPoolTaskExecutor::getActiveCount); Metrics.gauge( "thread.pool.thread.count" , consumerExecutorTAG, consumerExecutor, ThreadPoolTaskExecutor::getPoolSize); Metrics.gauge( "thread.pool.queue.size" , consumerExecutorTAG, consumerExecutor, e -> e.getThreadPoolExecutor().getQueue().size()); Metrics.gauge( "thread.pool.connectionCount" , okHttpExecutorTAG, connectionPool, ConnectionPool::connectionCount); Metrics.gauge( "thread.pool.idleConnectionCount" , okHttpExecutorTAG, connectionPool, ConnectionPool::idleConnectionCount); } catch (Exception e) { //ignore } }; @Override public void afterPropertiesSet() throws Exception { // 每5秒执行一次 scheduledExecutor.scheduleWithFixedDelay(monitor, 0 , 5 , TimeUnit.SECONDS); } } |
所有评论(0)