要獲取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的運行情況。