tomcat线程池监控,预警

1.启动类增加:

@EnableScheduling
2.如果springboot > 2.2的需要开启mbean注册,否则无法获取到线程池对象
server:
  port: 7080
  tomcat:
    mbeanregistry:
      enabled: true

3.增加处理类

private static MBeanServer mbeanServer;

private static ObjectName objectName = null;

static {
    try {
        objectName = new ObjectName("Tomcat:type=ThreadPool,*");
        mbeanServer = Registry.getRegistry(null, null).getMBeanServer();
    } catch (MalformedObjectNameException e) {
        log.error("TomcatThreadPoolMonitorJobErr",e);
    }
}

@Scheduled(cron = "0 */1 * * * ?")
public void execute() {
    try {

        // collect thread metrics
        Set<ObjectInstance> objectInstances = getObjectNames(objectName);
        for (ObjectInstance objectInstance : objectInstances) {
            // only check one
            ObjectName connectorName=objectInstance.getObjectName();
            String subType = connectorName.getKeyProperty("subType");
            if (StringUtil.isNotEmpty(subType) || !isTomcatServer(connectorName.getDomain())) {
                continue;
            }
            String name = ObjectName.unquote(connectorName.getKeyProperty("name"));
            // 基本不使用的协议
            if (name.startsWith("ajp")) {
                continue;
            }

            int currentThreadsBusy = (Integer) mbeanServer.getAttribute(connectorName, "currentThreadsBusy");
            log.info("tomcat.thread.pool.busyCount {}", currentThreadsBusy);

            int currentThreadCount = (Integer) mbeanServer.getAttribute(connectorName, "currentThreadCount");
            log.info("tomcat.thread.pool.currentCount {}", currentThreadCount);

            int minSpareThreads = (Integer) mbeanServer.getAttribute(connectorName, "minSpareThreads");
            log.info("tomcat.thread.pool.spareCount {}", minSpareThreads);

            int maxThreads = (Integer) mbeanServer.getAttribute(connectorName, "maxThreads");
            log.info("tomcat.thread.pool.maxCount {}", maxThreads);
        }
    } catch (Exception e) {
        log.error("Exception occur when getting connector global stats: ", e);
    }
}

public Set<ObjectInstance> getObjectNames(ObjectName objectName) {
    if (objectName == null) {
        return new HashSet<>();
    }
    Set<ObjectInstance> objectInstance = mbeanServer.queryMBeans(objectName,null);
    if (!objectInstance.isEmpty()) {
        return objectInstance;
    }
    return new HashSet<>();
}

private boolean isTomcatServer(String domain) {
    if (StringUtil.isEmpty(domain)) {
        return false;
    }
    return StringUtils.equalsIgnoreCase("tomcat", domain) ||
            StringUtils.equalsIgnoreCase("catalina", domain);
}

  

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值