监控应用服务器使用JMX监控Tomcat (推荐)
前言:做了一个监控应用服务器的项目(支持Tocmat、WebSphere、WebLogic各版本),
过程也算是磕磕绊绊,由于网上缺少相关资料,或者深陷于知识的海洋难以寻觅到有效的资料,因而走过不少弯路,遇过不少困难。为了留下点印记,给后来人留下
点经验之谈,助之少走弯路,故将这些经验整理出来,与大家分享。水平有限,难免疏漏,还望指正。如有疑问,欢迎留言,或者加入Q群参与讨
论:35526521。
一、激活Tomcat的JMX远程配置
要通过JMX远程监控Tomcat,首先需要激活Tomcat的JMX远程配置。
① 先修改Tomcat的启动脚本,windows下为bin/catalina.bat(linux下为catalina.sh),添加以下内容,8999是jmxremote使用的端口号,第二个false表示不需要鉴权:
Xml代码
set JMX_REMOTE_CONFIG=-Dcom.sun.management.jmxremote
-Dcom.sun.management.jmxremote.port=
-Dcom.sun.management.jmxremote.ssl=false
-Dcom.sun.management.jmxremote.authenticate=false
set CATALINA_OPTS=%CATALINA_OPTS% %JMX_REMOTE_CONFIG%
要注意以上语句的位置不能太后面,可以加在【if "%OS%" == "Windows_NT" setlocal】一句后的大段的注释后面。
参考官方说明:
http://tomcat.apache.org/tomcat-6.0-doc/monitoring.html#Enabling_JMX_Remote
② 上面的配置是不需要鉴权的,如果需要鉴权则添加的内容为:
Xml代码
set JMX_REMOTE_CONFIG=-Dcom.sun.management.jmxremote
-Dcom.sun.management.jmxremote.port=
-Dcom.sun.management.jmxremote.ssl=false
-Dcom.sun.management.jmxremote.authenticate=true
-Dcom.sun.management.jmxremote.password.file=../conf/jmxremote.password
-Dcom.sun.management.jmxremote.access.file=../conf/jmxremote.access
set CATALINA_OPTS=%CATALINA_OPTS% %JMX_REMOTE_CONFIG%
③ 然后复制并修改授权文件
$JAVA_HOME/jre/lib/management下有jmxremote.access和jmxremote.password的模板文件,将两个文件复制到$CATALINA_BASE/conf目录下
◆ 修改$CATALINA_BASE/conf/jmxremote.access 添加内容:
monitorRole readonly
controlRole readwrite
◆ 修改$CATALINA_BASE/conf/jmxremote.password 添加内容:
monitorRole tomcat
controlRole tomcat
注意: 如果进行了以上步骤导致Tomcat启动不了,那么很可能是密码文件的权限问题
需要修改jmxremote.password文件的访问权限,只有文件的owner所有者才能拥有访问权限 (并且文件的所有者必须与tomcat的所有者是同一用户):
Windows的NTFS文件系统下,选中文件,点右键 -->“属性”-->“安全”-->
点“高级”--> 点“更改权限”--> 去掉“从父项继承....”-->
弹出窗口中选“删除”,这样就删除了所有访问权限。再选“添加”--> “高级”-->
“立即查找”,选中你的用户(或用户组,如果选用户不行那就选用户组),点“确定",“确定"。来到权限项目窗口,勾选
“完全控制”,点“确定”,OK了。
官方的提示:
The password file should be read-only and only accessible by the operating system user Tomcat is running as.
④ 重新启动Tomcat,在Windows命令行输入“netstat -a”查看配置的端口号是否已打开,如果打开,说明上面的配置成功了。
⑤ 使用jconsole测试JMX。
运行$JAVA_HOME/bin目录下的jconsole.exe,打开J2SE监视和管理控制台,然后建立连接,如果是本地的Tomcat则
直接选择然后点击连接,如果是远程的,则进入远程选项卡,填写地址、端口号、用户名、口令即可连接。。Mbean属性页中给出了相应的数
据,Catalina中是tomcat的,java.lang是jvm的。对于加粗的黑体属性值,需双击一下才可看内容。
二、使用JMX监控Tomcat示例代码
Java代码
String jmxURL = "service:jmx:rmi:///jndi/rmi://192.168.10.93:8999/jmxrmi";
JMXServiceURL serviceURL = new JMXServiceURL(jmxURL); Map map = new HashMap();
// 用户名密码,在jmxremote.password文件中查看
String[] credentials = new String[] { "monitorRole", "tomcat" };
map.put("jmx.remote.credentials", credentials);
JMXConnector connector = JMXConnectorFactory.connect(serviceURL, map);
MBeanServerConnection mbsc = connector.getMBeanServerConnection(); // 端口最好是动态取得 name对应的是ThreadPool 的名称,会有变化,根据自己的设置修改
ObjectName threadObjName = new ObjectName("Catalina:type=ThreadPool,name=http-8080");
MBeanInfo mbInfo = mbsc.getMBeanInfo(threadObjName); // tomcat的线程数对应的属性值
String attrName = "currentThreadCount";
MBeanAttributeInfo[] mbAttributes = mbInfo.getAttributes();
System.out.println("currentThreadCount:" + mbsc.getAttribute(threadObjName, attrName));
三、完整的示例代码文件
Java代码
import java.lang.management.MemoryUsage;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set; import javax.management.MBeanAttributeInfo;
import javax.management.MBeanInfo;
import javax.management.MBeanServerConnection;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL; public class JMXTest { /**
* @param args
*/
public static void main(String[] args) {
try { String jmxURL = "service:jmx:rmi:///jndi/rmi://127.0.0.1:8999/jmxrmi"; JMXServiceURL serviceURL = new JMXServiceURL(jmxURL); Map map = new HashMap();
String[] credentials = new String[] { "monitorRole", "tomcat" };
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();
}
}
实例2:
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));
}
}
监控应用服务器使用JMX监控Tomcat (推荐)的更多相关文章
- 性能测试之监控--zabbix通过jmx监控tomcat
前提: 已经安装好了zabbix server 实验环境 Centos 7 Zabbix 3.0 Tomcat 7.0 JDK 1.8 安装JDK tar -zxvf jdk-8u181-linux- ...
- Java 监控基础 - 使用 JMX 监控和管理 Java 程序
点赞再看,动力无限.Hello world : ) 微信搜「程序猿阿朗 」. 本文 Github.com/niumoo/JavaNotes 和 未读代码网站 已经收录,有很多知识点和系列文章. 此篇文 ...
- Tomcat调优及JMX监控
Tomcat调优及JMX监控 实验背景 ====================================================== 系统版本:CentOS release 6.5 ( ...
- zabbix通过jmx监控tomcat
Zabbix版本: Zabbix 3.0.2 一.服务端配置 1.安装jdk(版本1.7.0_79) 安装与配置比较简单,过程省略.执行java -version命令,出现类似界面表示成功. 2. ...
- zabbix 基于JMX的Tomcat监控
zabbix 基于JMX的Tomcat监控 一.环境 ubuntu14.04 LTS Java 1.7.0 zabbix 2.4.5 二.安装配置 1.安装JavaGateway 在ubuntu14. ...
- Zabbix JMX之tomcat监控
工作原理: 1.JAVA-GATEWAY Zabbix本身不支持直接监控Java,在zabbix 1.8以前,只能使用Zapcat来做代理监控,而且要修改源代码,非常麻烦.所有后来为了解决这个监控问 ...
- zabbix监控tomcat(使用jmx监控,但不使用系统自带模版)
一,zabbx使用jmx监控tomcat的原理分析 1.Zabbix-Server找Zabbix-Java-Gateway获取Java数据 2.Zabbix-Java-Gateway找Java程序(j ...
- zabbix使用jmx监控tomcat
zabbix监控Tomcat/JVM实例性能(115) – 运维生存时间http://www.ttlsa.com/zabbix/zabbix-use-jmx-monitor-tomcat/ zabbi ...
- Linux记录-JMX监控Tomcat上传到falcon
1.登录测试服务器xxxxxx xxxxxx su root输入xxxx 2.先修改Tomcat的启动脚本,(linux下为catalina.sh),添加以下内容: CATALINA_OPTS=&qu ...
随机推荐
- [BZOJ1491][NOI2007]社交网络 floyd
1491: [NOI2007]社交网络 Time Limit: 10 Sec Memory Limit: 64 MBSubmit: 2196 Solved: 1170[Submit][Status ...
- [thinkphp] 是如何输出一个页面的
表面上看,TP输出一个页面很简单:$this->display(); 实际上是怎么回事呢?$this->display(); 这个display()方法是定义在ThinkPHP/Libra ...
- POJ 1008 Maya Calendar / UVA 300【日期转换/常量数组】
Maya Calendar Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 82431 Accepted: 25319 Descr ...
- F - Oil Deposits 【地图型BFS+联通性】
The GeoSurvComp geologic survey company is responsible for detecting underground oil deposits. GeoSu ...
- CentOS下MySQL主从复制,读写分离
1.环境:所有系统都是CentOS5.5 mysql-5.6.31-2.el5,MySQL中都没有数据 主服务器IP为192.168.128.230 从服务器IP为192.168.128.235 代理 ...
- python 连接数据库练习
#!/usr/bin/python# -*- coding:utf-8 -*-import logginglogging.basicConfig(level=logging.INFO)import m ...
- 【强联通分量缩点】【搜索】bzoj2208 [Jsoi2010]连通数
两次dfs缩点,然后n次dfs暴搜. #include<cstdio> #include<vector> #include<cstring> using names ...
- 友情链接&部分题目的密码
YPL: https://www.cnblogs.com/Sdchr/ ZWL: https://www.cnblogs.com/acha XJ: https://blog.csdn.net/boyx ...
- golang技巧-接口型函数
接口型函数:指的是用函数实现接口,这样在调用的时候就会非常简便,这种函数为接口型函数,这种方式适用于只有一个函数的接口. 定义一个类型,这个类型只定义了函数的参数列表,函数参数列表与接口定义的方法一致 ...
- 两道Java面试题!
body { font-family: 微软雅黑; font-size: 14px; line-height: 2; } html, body { color: inherit; background ...