上一篇博客Tomcat学习--war服务相关状态信息监控中我们已经了解了一下对war包的启动、停止、运行状态、重载和卸载操作的实现机制,接下来我们用这篇博客了解一下tomcat运行过程中服务器,操作系统,jvm和war的一些状态信息。
目前tomcat将运行的过程中的一些状态信息通过JMX的MBeanServer机制保存起来,所以目前的实现就是通过MBeanServer来获取数据就好,可以参考tomcat的StatusManagerServlet的实现逻辑。
本篇博客只是简单的获取了一些数据进行展示
1、web.xml中配置如下
tomcat-monitor-info
com.tianjunwei.tomcat.servlet.MonitorInfoServlet
tomcat-monitor-info
/tomcat_monitor_info
2、实现源码如下:
public class MonitorInfoServlet extends HttpServlet implements NotificationListener {
private static final long serialVersionUID = 1L;
protected static MBeanServer mBeanServer = null;
protected final Vector protocolHandlers = new Vector<>();
protected final Vector threadPools = new Vector<>();
protected final Vector globalRequestProcessors = new Vector<>();
protected final Vector requestProcessors = new Vector<>();
@Override
public void init() throws ServletException {
// Retrieve the MBean server
mBeanServer = Registry.getRegistry(null, null).getMBeanServer();
try {
// Query protocol handlers
String onStr = "*:type=ProtocolHandler,*";
ObjectName objectName = new ObjectName(onStr);
Set set = mBeanServer.queryMBeans(objectName, null);
Iterator iterator = set.iterator();
while (iterator.hasNext()) {
ObjectInstance oi = iterator.next();
protocolHandlers.addElement(oi.getObjectName());
}
// Query Thread Pools
onStr = "*:type=ThreadPool,*";
objectName = new ObjectName(onStr);
set = mBeanServer.queryMBeans(objectName, null);
iterator = set.iterator();
while (iterator.hasNext()) {
ObjectInstance oi = iterator.next();
threadPools.addElement(oi.getObjectName());
}
// Query Global Request Processors
onStr = "*:type=GlobalRequestProcessor,*";
objectName = new ObjectName(onStr);
set = mBeanServer.queryMBeans(objectName, null);
iterator = set.iterator();
while (iterator.hasNext()) {
ObjectInstance oi = iterator.next();
globalRequestProcessors.addElement(oi.getObjectName());
}
// Query Request Processors
onStr = "*:type=RequestProcessor,*";
objectName = new ObjectName(onStr);
set = mBeanServer.queryMBeans(objectName, null);
iterator = set.iterator();
while (iterator.hasNext()) {
ObjectInstance oi = iterator.next();
requestProcessors.addElement(oi.getObjectName());
}
// Register with MBean server
onStr = "JMImplementation:type=MBeanServerDelegate";
objectName = new ObjectName(onStr);
mBeanServer.addNotificationListener(objectName, this, null, null);
} catch (Exception e) {
e.printStackTrace();
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException{
PrintWriter writer = response.getWriter();
Map dataMap = new HashMap();
dataMap.put("server", getServerData());
dataMap.put("os", getOsData());
dataMap.put("jvm", getJVMData());
dataMap.put("war", getWarData());
writer.write(JSON.toJSONString(dataMap));
writer.flush();
}
/**
* 获取操作系统及jvm相关的信息
*/
public static Map getServerData(){
Map serverMap =new HashMap();
serverMap.put("tomcat_version", ServerInfo.getServerInfo());
serverMap.put("jvm_version", System.getProperty("java.runtime.version"));
serverMap.put("jvm_vendor", System.getProperty("java.vm.vendor"));
serverMap.put("os_name", System.getProperty("os.name"));
serverMap.put("os_version", System.getProperty("os.version"));
serverMap.put("os_arch", System.getProperty("os.arch"));
try {
InetAddress address = InetAddress.getLocalHost();
serverMap.put("hostName", address.getHostName());
serverMap.put("hostAddress", address.getHostAddress());
} catch (UnknownHostException e) {
serverMap.put("hostName", "-");
serverMap.put("hostAddress", "-");
}
return serverMap;
}
/**
*
* 获取操作系统相关信息
*/
public static Map getOsData(){
Map osMap = new HashMap();
long[] result = new long[16];
boolean ok = false;
try {
String methodName = "info";
Class paramTypes[] = new Class[1];
paramTypes[0] = result.getClass();
Object paramValues[] = new Object[1];
paramValues[0] = result;
Method method = Class.forName("org.apache.tomcat.jni.OS")
.getMethod(methodName, paramTypes);
method.invoke(null, paramValues);
ok = true;
} catch (Throwable t) {
t = ExceptionUtils.unwrapInvocationTargetException(t);
ExceptionUtils.handleThrowable(t);
}
if (ok) {
osMap.put(" Physical memory",formatSize(Long.valueOf(result[0]), true));
osMap.put(" Available memory: ",formatSize(Long.valueOf(result[1]), true));
osMap.put(" Total page file: ",formatSize(Long.valueOf(result[2]), true));
osMap.put(" Free page file: ",formatSize(Long.valueOf(result[3]), true));
osMap.put(" Memory load: ",Long.valueOf(result[6]));
osMap.put(" Process kernel time: ",formatTime(Long.valueOf(result[11] / 1000), true));
osMap.put(" Process user time: ",formatTime(Long.valueOf(result[12] / 1000), true));
}
return osMap;
}
public static Map getJVMData(){
Map jvmMap = new HashMap();
SortedMap memoryPoolMBeans = new TreeMap<>();
for (MemoryPoolMXBean mbean: ManagementFactory.getMemoryPoolMXBeans()) {
String sortKey = mbean.getType() + ":" + mbean.getName();
memoryPoolMBeans.put(sortKey, mbean);
}
jvmMap.put("free_memory",Runtime.getRuntime().freeMemory());
jvmMap.put("total_memory",Runtime.getRuntime().totalMemory());
jvmMap.put("max_memory" , Runtime.getRuntime().maxMemory());
List
3、获取的结果数据如下:
{
"jvm": {
"total_memory": 48758784,
"memory_pool": [{
"usageMax": 11010048,
"name": "PS Eden Space",
"usageUsed": 6111136,
"type": "HEAP",
"usageCommitted": 10485760,
"usageInit": 13107200
}, {
"usageMax": 35127296,
"name": "PS Old Gen",
"usageUsed": 19668376,
"type": "HEAP",
"usageCommitted": 35127296,
"usageInit": 35127296
}, {
"usageMax": 3145728,
"name": "PS Survivor Space",
"usageUsed": 1950184,
"type": "HEAP",
"usageCommitted": 3145728,
"usageInit": 2097152
}, {
"usageMax": 104857600,
"name": "Code Cache",
"usageUsed": 11987072,
"type": "NON_HEAP",
"usageCommitted": 12255232,
"usageInit": 2555904
}, {
"usageMax": 1073741824,
"name": "Compressed Class Space",
"usageUsed": 3185400,
"type": "NON_HEAP",
"usageCommitted": 3538944,
"usageInit": 0
}, {
"usageMax": -1,
"name": "Metaspace",
"usageUsed": 31663032,
"type": "NON_HEAP",
"usageCommitted": 32636928,
"usageInit": 0
}],
"free_memory": 21029088,
"max_memory": 48758784
},
"server": {
"hostName": "nb-hz20036325",
"tomcat_version": "Apache Tomcat/8.5.24",
"jvm_vendor": "Oracle Corporation",
"os_version": "6.1",
"os_arch": "amd64",
"os_name": "Windows 7",
"hostAddress": "10.13.80.12",
"jvm_version": "1.8.0_151-b12"
},
"os": {
" Free page file: ": 17006,
" Available memory: ": 4869,
" Physical memory": 12241,
" Process user time: ": "12.324 s",
" Total page file: ": 24481,
" Process kernel time: ": "7.254 s",
" Memory load: ": 60
},
"war": {
"requestCount": 112,
"connectionCount": 2,
"currentThreadCount": 10,
"memoryMax": 48758784,
"metaspaceUse": 30,
"contexts": [{
"requestCount": 0,
"sessions": [],
"sessionCount": 0,
"name": "/examples",
"state": "STARTED",
"errorCount": 0
}, {
"requestCount": 0,
"sessions": [],
"sessionCount": 0,
"name": "/host-manager",
"state": "STARTED",
"errorCount": 0
}, {
"requestCount": 48,
"sessions": [{
"inactiveIntervalTime": 1800,
"lastAcessTime": 1525247083747,
"sessionId": "11C58869BBF32D217EFF3F8B725982E6",
"idleTIme": 612935
}],
"sessionCount": 1,
"name": "/manager",
"state": "STARTED",
"errorCount": 1
}, {
"requestCount": 9,
"sessions": [],
"sessionCount": 0,
"name": "/docs",
"state": "STARTED",
"errorCount": 0
}, {
"requestCount": 2,
"sessions": [],
"sessionCount": 0,
"name": "/war_mointor",
"state": "STARTED",
"errorCount": 0
}],
"maxThreads": 200,
"errorCount": 4,
"memoryUse": 27729696,
"uptime": 11892453,
"metaspaceMax": 0,
"maxConnections": 10000
}
}
代码地址 Github