Tomcatの実行状態をJavaで取得する方法
要获取Tomcat的运行情况,可以使用以下方法:
- MBeanサーバ接続
- オブジェクト名
- 属性を取得する
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);
// ...
}
}
- Tomcatが提供する管理インターフェース(管理画面、管理APIなど)から、Tomcatの稼働状況を取得します。HTTPリクエストでTomcatの状態情報(接続数、スレッドプールの使用状況など)を取得できます。
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の動作にアクセスするための十分な権限があることを確認してください。