要获取Tomcat的运行情况,可以使用以下方法:
MBeanServerConnection
和ObjectName
类来连接Tomcat的MBean服务器,并通过MBean的getAttribute
方法获取属性值。import java.lang.management.ManagementFactory;
import javax.management.MBeanServer;
import javax.management.ObjectName;
public class TomcatStatus {
public static void main(String[] args) throws Exception {
// 获取MBean服务器
MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
// 设置Tomcat的ObjectName
ObjectName objectName = new ObjectName("Catalina:type=ThreadPool,name=\"http-nio-8080\"");
// 获取属性值
int currentThreadCount = (int) mBeanServer.getAttribute(objectName, "currentThreadCount");
// ...
// 输出属性值
System.out.println("当前线程数:" + currentThreadCount);
// ...
}
}
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class TomcatStatus {
public static void main(String[] args) throws Exception {
// 设置Tomcat的管理接口URL
URL url = new URL("http://localhost:8080/manager/status?XML=true");
// 创建HTTP连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setRequestProperty("Authorization", "Basic " + Base64.getEncoder().encodeToString("admin:password".getBytes()));
// 发送请求
int responseCode = connection.getResponseCode();
// 读取响应
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// 输出响应
System.out.println("响应代码:" + responseCode);
System.out.println("响应内容:" + response.toString());
}
}
注意:以上方法需要在Tomcat的运行环境中执行,并确保有足够的权限来访问Tomcat的运行情况。