关闭

Java之——使用JMX监控Tomcat

标签: javajmxtomcat
18873人阅读 评论(1) 收藏 举报
分类:

转载请注明出处:http://blog.csdn.net/l1028386804/article/details/51547408

2016年5月的最后一天,今天我将和大家分享Java中如何使用JMX来监控Tomcat的各种状态。好了,不多说了,我们直接进入主题

一、激活Tomcat的JMX远程配置

要通过JMX远程监控Tomcat,首先需要激活Tomcat的JMX远程配置。

① 修改脚本

先修改Tomcat的启动脚本,windows下为bin/catalina.bat(linux下为catalina.sh),添加以下内容,8999是jmxremote使用的端口号,第二个false表示不需要鉴权:

set JMX_REMOTE_CONFIG=-Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=8999 -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

http://tomcat.apache.org/tomcat-7.0-doc/monitoring.html#Enabling_JMX_Remote

http://tomcat.apache.org/tomcat-8.0-doc/monitoring.html#Enabling_JMX_Remote

http://tomcat.apache.org/tomcat-9.0-doc/monitoring.html#Enabling_JMX_Remote

② 鉴权

上面的配置是不需要鉴权的,如果需要鉴权则添加的内容为:

set JMX_REMOTE_CONFIG=-Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=8999 -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 chenfeng
     controlRole chenfeng
注意: 如果进行了以上步骤导致Tomcat启动不了,那么很可能是密码文件的权限问题
需要修改jmxremote.password文件的访问权限,只有运行Tomcat的用户才能拥有访问权限 :
      Windows的NTFS文件系统下,选中文件,点右键 -->“属性”-->“安全”--> 点“高级”--> 点“更改权限”--> 去掉“从父项继承....”--> 弹出窗口中选“删除”,这样就删除了所有访问权限。再选“添加”--> “高级”--> “立即查找”,选中你的用户(或用户组,如果选用户不行那就选用户组),例administrator,点“确定",“确定"。来到权限项目窗口,勾选“完全控制”,点“确定”,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示例代码

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();

// 端口最好是动态取得
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));

三、完整的示例代码文件

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;
/**
 * @author liuyazhuang
 * @date 2016-05-31 
 */
public class JMXTest {

	/**
	 * main方法
	 * @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();
	}
}

1
0
查看评论
发表评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场

使用JMX监控Tomcat

一、激活Tomcat的JMX远程配置 要通过JMX远程监控Tomcat,首先需要激活Tomcat的JMX远程配置。 ① 先修改Tomcat的启动脚本,windows下为bin/ca...
  • junehappylove
  • junehappylove
  • 2016-10-26 21:11
  • 3019

JMX监控Tomcat

环境:Tomcat5.5、jdk61、先配Tomcat的启动语句,window下tomcat的bin/catalina.bat(linux为catalina.sh),在头上注释部分(.bat为rem、...
  • airobot008
  • airobot008
  • 2009-03-03 08:22
  • 27765

Tomcat开启JMX监控

Tomcat系统运行过程出现错误,需要打开JMX,添加对JVM的监控。Tomcat运行在CentOS中。
  • dongdong2980
  • dongdong2980
  • 2017-11-08 11:06
  • 72

Windows下利用JMX监控Tomcat

windowstomcatJMX 环境:window XP + tomcat6.0 + jdk1.5 步骤: 1.修改Tomcat目录下的bin/catalina.bat。 2.在该文件中查找...
  • lilin520530
  • lilin520530
  • 2017-04-07 13:56
  • 548

开启jmx监控后关闭tomcat提示Port already in use的问题

linux中关闭tomcat失败,提示port already in use错误。 Stopping Tomcat Using CATALINA_BASE:   /usr/local/to...
  • u010166386
  • u010166386
  • 2017-04-18 18:16
  • 365

linux下使用JMX监控tomcat

1、JMX: JMX(Java Management Extensions)Java管理扩展,是一个为应用程序植入管理功能的框架,是一套标准的代理跟服务。总而言之,它可以使得基于java语言开发的程...
  • liuxiao723846
  • liuxiao723846
  • 2015-12-15 18:06
  • 1973

使用JMX监控Tomcat

1,什么是JMX        JMX是一种JAVA的正式规范,它主要目的是让程序有被管理的功能,那么怎么理解所谓的“被管理”呢?试想你开发了一个软件(如WEB网站),它是在24小时不间断运行的,那...
  • done58
  • done58
  • 2016-04-13 15:45
  • 643

利用JMX监控Tomcat集群

JMX是Sun在Java5中提出的一种用于监控JVM运行状态的框架和规范,通过JMX可以很方便的检测Tomcat集群各个节点的运行状况。了解JMX可以看这篇文章http://www.ibm.com/d...
  • u013614451
  • u013614451
  • 2014-06-30 13:22
  • 1337

linux tomcat8 配置 jmx监控

linux tomcat8 配置 jmx监控linux tomcat8 配置 jmx监控 编辑tomcatbincatalinash 编辑jmxremoteaccess和jmxremotepasswo...
  • pinyitianle
  • pinyitianle
  • 2016-04-17 10:36
  • 1913

jmx 监控 tomcat

  • 2011-12-01 22:16
  • 113KB
  • 下载
    个人资料
    • 访问:1997400次
    • 积分:26015
    • 等级:
    • 排名:第259名
    • 原创:803篇
    • 转载:9篇
    • 译文:0篇
    • 评论:297条
    博客专栏
    Android

    文章:80篇

    阅读:230993
    Python

    文章:49篇

    阅读:33188
    搜索优化

    文章:20篇

    阅读:25353
    Nginx

    文章:17篇

    阅读:52840
    Dubbo

    文章:20篇

    阅读:41053
    JMS

    文章:13篇

    阅读:11185
    Netty

    文章:1篇

    阅读:1722
    Redis

    文章:18篇

    阅读:90322
    Memcached

    文章:9篇

    阅读:44713
    设计模式

    文章:22篇

    阅读:47706
    Mycat

    文章:20篇

    阅读:25011
    Web前端

    文章:22篇

    阅读:81780
    Linux

    文章:76篇

    阅读:219046
    JVM

    文章:15篇

    阅读:50177
    J2EE

    文章:74篇

    阅读:271670
    Java

    文章:152篇

    阅读:494169
    Hadoop生态

    文章:125篇

    阅读:194677
    MySQL

    文章:129篇

    阅读:254688
    最新评论