运用JMX监控Tomcat
1、先配Tomcat的启动语句,window下tomcat的bin/catalina.bat(linux为catalina.sh),在头上注释部分(.bat为rem、.sh为#)后面加上set JAVA_OPTS=-Dcom.sun.management.jmxremote.port=8999 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=true
(linux为JAVA_OPTS=-Dcom.sun.management.jmxremote.port=8999 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=true)
2、修改jmx远程访问授权。默认为JAVA_HOME/jre/lib/management下jmxremote.access、jmxremote.password(缺省系统提供了个模版jmxremote.password.template改下名就成)
注意:linux下需要该权限,chmod 600 jmxremote.access, chmod 600 jmxremote.password
window下特麻烦,现需要jdk装在NTFS文件系统下,选中文件,点右键“属性”-〉安全,点“高级”,去掉“从父项继承....”,弹出窗口中选“删除”,这样删除了所有访问权限。再选“添加”-〉高级,“立即查找”,选中你的用户,例administrator,点“确定",“确定"。来到权限窗口,勾选"完全控制",点"确定",OK了。
3、用jconsole连接远程linux服务时, IP地址和port都输入正确的情况下,仍然是连接失败
vi /etc/hosts,将hostname对应的IP改为真实IP
4、测试JMX。启动tomcat,在window“命令行窗口”中输入netstat -an看下8999端口打开没有。若没有,则前面没配对。若已打开,则可在另一台机器的“命令行窗口”中输入jconsole,打开jdk自带的jmx客户端。选远程连接,录入tomcat所在机器的IP,端口例192.168.10.10:8999,帐号、密码在jmxremote.password中,如帐号controlRole,密码R&D(缺省monitorRole只能读,controlRole能读写,jmxremote.access中可配置)。点“连接”。看到图就行了。
5、关于数据。Mbean属性页中给出了相应的数据,Catalina中是tomcat的,java.lang是jvm的。对于加粗的黑体属性值,需双击一下才可看内容
5、关于编程。
public class JMXTest {
/**
* @param args
*/
public static void main(String[] args) {
try {
String jmxURL = "service:jmx:rmi:///jndi/rmi://192.168.10.93:8999/jmxrmi";//tomcat jmx url
JMXServiceURL serviceURL = new JMXServiceURL(jmxURL);
Map map = new HashMap();
String[] credentials = new String[] { "monitorRole" , "QED" };
map.put("jmx.remote.credentials", credentials);
JMXConnector connector = JMXConnectorFactory.connect(serviceURL, map);
MBeanServerConnection mbsc = connector.getMBeanServerConnection();
//端口最好是动态取得
ObjectName threadObjName = new ObjectName("Catalina:type=ThreadPool,name=http-8080");
MBeanInfo mbInfo = mbsc.getMBeanInfo(threadObjName);
String attrName = "currentThreadCount";//tomcat的线程数对应的属性值
MBeanAttributeInfo[] mbAttributes = mbInfo.getAttributes();
System.out.println("currentThreadCount:"+mbsc.getAttribute(threadObjName, attrName));
//heap
for(int j=0;j <mbsc.getDomains().length;j++){
System.out.println("###########"+mbsc.getDomains()[j]);
}
Set MBeanset = mbsc.queryMBeans(null, null);
System.out.println("MBeanset.size() : " + MBeanset.size());
Iterator MBeansetIterator = MBeanset.iterator();
while (MBeansetIterator.hasNext()) {
ObjectInstance objectInstance = (ObjectInstance)MBeansetIterator.next();
ObjectName objectName = objectInstance.getObjectName();
String canonicalName = objectName.getCanonicalName();
System.out.println("canonicalName : " + canonicalName);
if (canonicalName.equals("Catalina:host=localhost,type=Cluster")) {
// Get details of cluster MBeans
System.out.println("Cluster MBeans Details:");
System.out.println("=========================================");
//getMBeansDetails(canonicalName);
String canonicalKeyPropList = objectName.getCanonicalKeyPropertyListString();
}
}
//------------------------- system ----------------------
ObjectName runtimeObjName = new ObjectName("java.lang:type=Runtime");
System.out.println("厂商:"+ (String)mbsc.getAttribute(runtimeObjName, "VmVendor"));
System.out.println("程序:"+ (String)mbsc.getAttribute(runtimeObjName, "VmName"));
System.out.println("版本:"+ (String)mbsc.getAttribute(runtimeObjName, "VmVersion"));
Date starttime=new Date((Long)mbsc.getAttribute(runtimeObjName, "StartTime"));
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("启动时间:"+df.format(starttime));
Long timespan=(Long)mbsc.getAttribute(runtimeObjName, "Uptime");
System.out.println("连续工作时间:"+JMXTest.formatTimeSpan(timespan));
//------------------------ JVM -------------------------
//堆使用率
ObjectName heapObjName = new ObjectName("java.lang:type=Memory");
MemoryUsage heapMemoryUsage = MemoryUsage.from((CompositeDataSupport)mbsc.getAttribute(heapObjName, "HeapMemoryUsage"));
long maxMemory = heapMemoryUsage.getMax();//堆最大
long commitMemory = heapMemoryUsage.getCommitted();//堆当前分配
long usedMemory = heapMemoryUsage.getUsed();
System.out.println("heap:"+(double)usedMemory*100/commitMemory+"%");//堆使用率
MemoryUsage nonheapMemoryUsage = MemoryUsage.from((CompositeDataSupport)mbsc.getAttribute(heapObjName, "NonHeapMemoryUsage"));
long noncommitMemory = nonheapMemoryUsage.getCommitted();
long nonusedMemory = heapMemoryUsage.getUsed();
System.out.println("nonheap:"+(double)nonusedMemory*100/noncommitMemory+"%");
ObjectName permObjName = new ObjectName("java.lang:type=MemoryPool,name=Perm Gen");
MemoryUsage permGenUsage = MemoryUsage.from((CompositeDataSupport)mbsc.getAttribute(permObjName, "Usage"));
long committed = permGenUsage.getCommitted();//持久堆大小
long used = heapMemoryUsage.getUsed();//
System.out.println("perm gen:"+(double)used*100/committed+"%");//持久堆使用率
//-------------------- Session ---------------
ObjectName managerObjName = new ObjectName("Catalina:type=Manager,*");
Set<ObjectName> s=mbsc.queryNames(managerObjName, null);
for (ObjectName obj:s){
System.out.println("应用名:"+obj.getKeyProperty("path"));
ObjectName objname=new ObjectName(obj.getCanonicalName());
System.out.println("最大会话数:"+ mbsc.getAttribute( objname, "maxActiveSessions"));
System.out.println("会话数:"+ mbsc.getAttribute( objname, "activeSessions"));
System.out.println("活动会话数:"+ mbsc.getAttribute( objname, "sessionCounter"));
}
//----------------- Thread Pool ----------------
ObjectName threadpoolObjName = new ObjectName("Catalina:type=ThreadPool,*");
Set<ObjectName> s2=mbsc.queryNames(threadpoolObjName, null);
for (ObjectName obj:s2){
System.out.println("端口名:"+obj.getKeyProperty("name"));
ObjectName objname=new ObjectName(obj.getCanonicalName());
System.out.println("最大线程数:"+ mbsc.getAttribute( objname, "maxThreads"));
System.out.println("当前线程数:"+ mbsc.getAttribute( objname, "currentThreadCount"));
System.out.println("繁忙线程数:"+ mbsc.getAttribute( objname, "currentThreadsBusy"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static String formatTimeSpan(long span){
long minseconds = span % 1000;
span = span /1000;
long seconds = span % 60;
span = span / 60;
long mins = span % 60;
span = span / 60;
long hours = span % 24;
span = span / 24;
long days = span;
return (new Formatter()).format("%1$d天 %2$02d:%3$02d:%4$02d.%5$03d", days,hours,mins,seconds,minseconds).toString();
}
}
另外实例:
public ConcurrentHashMap<String, Object> parseJMS(String tempid, ConcurrentHashMap<String, Object> paraMap) {
MBeanServerConnection mbsc = null;
try {
mbsc = connector.getMBeanServerConnection();
// ------------------------- system ----------------------
ObjectName runtimeObjName = new ObjectName("java.lang:type=Runtime");
TabularDataSupport system = (TabularDataSupport) mbsc.getAttribute(runtimeObjName, "SystemProperties");
//JVM版本
paraMap.put(tempid + "_JVMVERSION", mbsc.getAttribute(runtimeObjName, "VmVersion"));
//JVM厂商
paraMap.put(tempid + "_JVMMANUFACTURER", mbsc.getAttribute(runtimeObjName, "VmVendor"));
//系统结构
paraMap.put(tempid + "_SYSTEMSTRUCTURE", system.get(new Object[] {"os.arch"}).get("value"));
//操作系统
paraMap.put(tempid + "_OPERATIONSYSTEM", system.get(new Object[] {"os.name"}).get("value"));
//操作系统版本
paraMap.put(tempid + "_OPERATIONSYSTEMVERSION", system.get(new Object[] {"os.version"}).get("value"));
//Tomcat版本
String t_version = (String) system.get(new Object[] {"org.apache.catalina.startup.TldConfig.jarsToSkip"}).get("value");
paraMap.put(tempid + "_TOMCATVERSION", t_version == null ? "" : t_version.substring(0, t_version.indexOf("-")));
//链接Tomcat服务器的响应时间 -------------
ObjectName heapObjName = new ObjectName("java.lang:type=Memory");
MemoryUsage heapMemoryUsage = MemoryUsage.from((CompositeDataSupport)mbsc.getAttribute(heapObjName, "HeapMemoryUsage"));
//JVM已用内存
paraMap.put(tempid + "_JVMUSERDMEMORY", heapMemoryUsage.getUsed());
//JVM可用内存
paraMap.put(tempid + "_JVMAVAILABLEMEMORY", heapMemoryUsage.getCommitted() - heapMemoryUsage.getUsed());
//JVM内存总数
paraMap.put(tempid + "_JVMTOTALMEMORY", heapMemoryUsage.getCommitted());
//----------------- GlobalRequestProcessor ----------------
ObjectName requestProcessor = new ObjectName("Catalina:type=GlobalRequestProcessor,*");
Set<ObjectName> s2 = mbsc.queryNames(requestProcessor, null);
long bytesSents = 0;
long bytesReceiveds = 0;
Integer errorCounts = 0;
Integer requestCounts = 0;
long processingTimes = 0;
long maxTimes = 0;
for (ObjectName obj : s2) {
ObjectName objname = new ObjectName(obj.getCanonicalName());
long bytesSent = (long) mbsc.getAttribute( objname, "bytesSent");
long bytesReceived = (long) mbsc.getAttribute( objname, "bytesReceived");
Integer errorCount = (Integer) mbsc.getAttribute( objname, "errorCount");
Integer requestCount = (Integer) mbsc.getAttribute( objname, "requestCount");
long processingTime = (long) mbsc.getAttribute( objname, "processingTime");
long maxTime = (long) mbsc.getAttribute( objname, "maxTime");
bytesSents += bytesSent;
bytesReceiveds += bytesReceived;
errorCounts += errorCount;
requestCounts += requestCount;
processingTimes += processingTime;
maxTimes += maxTime;
}
//发送字节
paraMap.put(tempid + "_SENDBYTE", bytesSents);
//接收字节
paraMap.put(tempid + "_RECIEVEDBYTE", bytesReceiveds);
//错误个数
paraMap.put(tempid + "_ERRORNUMBER", errorCounts);
//请求个数
paraMap.put(tempid + "_REQUESTNUMBER", requestCounts);
//处理时间
paraMap.put(tempid + "_TREATMENTTIME", processingTimes);
//最大处理时间
paraMap.put(tempid + "_MAXTREATMENTTIME", maxTimes);
//----------------- Thread Pool ----------------
ObjectName threadpoolObjName = new ObjectName("Catalina:type=ThreadPool,*");
Set<ObjectName> tp = mbsc.queryNames(threadpoolObjName, null);
int currentThreadsBusys = 0;
int maxThreadss = 0;
for (ObjectName obj : tp) {
ObjectName objname = new ObjectName(obj.getCanonicalName());
int currentThreadsBusy = (int) mbsc.getAttribute( objname, "currentThreadsBusy");
int maxThreads = (int) mbsc.getAttribute( objname, "maxThreads");
currentThreadsBusys += currentThreadsBusy;
maxThreadss += maxThreads;
}
//当前忙碌线程数
paraMap.put(tempid + "_CURRENTBUSYTHREADSNUMBER", currentThreadsBusys);
//最大线程数
paraMap.put(tempid + "_MAXTHREADSNUMBER", maxThreadss);
//----------------- RequestProcessor ----------------
ObjectName requestProcessor1 = new ObjectName("Catalina:type=RequestProcessor,*");
Set<ObjectName> rp = mbsc.queryNames(requestProcessor1, null);
long requestProcessingTimes = 0;
int portCount = 0;
for (ObjectName obj : rp) {
portCount++;
ObjectName objname = new ObjectName(obj.getCanonicalName());
long requestProcessingTime = (long) mbsc.getAttribute(objname, "requestProcessingTime");
requestProcessingTimes += requestProcessingTime;
}
//端口平均响应时间
paraMap.put(tempid + "_AVERAGERESPONSETIME", portCount == 0 ? requestProcessingTimes : Math.round(requestProcessingTimes/portCount));
} catch (IOException e) {
e.printStackTrace();
} catch (MalformedObjectNameException e) {
e.printStackTrace();
} catch (AttributeNotFoundException e) {
e.printStackTrace();
} catch (InstanceNotFoundException e) {
e.printStackTrace();
} catch (MBeanException e) {
e.printStackTrace();
} catch (ReflectionException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
return paraMap;
}
public static void main(String[] args) {
DoJob job = new DoJob();
String tempid = "MW_WS_TOMCAT_AGENT";
job.connector = TomcatUtil.getJMXOfTomcat("service:jmx:rmi:///jndi/rmi://191.168.2.31:8999/jmxrmi", "", "");
ConcurrentHashMap<String, Object> paraMap = new ConcurrentHashMap<String, Object>();
paraMap = job.parseJMS(tempid, paraMap);
Iterator<String> it = paraMap.keySet().iterator();
while(it.hasNext()) {
String key = it.next();
System.out.println(key + " : " + paraMap.get(key));
}
}