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);
}
版权声明:本文为qq_19550657原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。