监控Tomcat解决方案(监控应用服务器系列文章一)
前言:最近在做一个监控应用服务器(Tocmat、WebSphere、WebLogic)的项目,目前已小有规模,回 头看看,一路走来,也算是磕磕绊绊,遇到过种种问题,走过不少弯路,不过程序员最不怕的就是遇到问题——有什么问题就解决什么问题。为了给后来人留下点经 验之谈,助之少走弯路,特意把这些经验整理出来,与大家分享。水平有限,难免疏漏,还望指正。如有疑问,可以Q我:562116039。
对监控 Tomcat的前期方案调研,共有两种方案,比较如下
使用Tomcat提供的manager应用进行数据采集
◆ 可以使用现有的成熟代码,减少工作量
◆ 支持各不同版本时无差别
◆ 可能存在特殊需求而manager不能满足的情况
◆ 最重要的一个优点是,配置比较简单
使用JMX接口开发监控程序
◆ 全部代码需要从零开始,代码量较大
◆ 支持各不同版本比较麻烦,每个版本可能有差异
◆ 可支配性强
◆ 最重要的一个缺点是,配置比较麻烦
方案一、使用 Tomcat提供的manager应用进行数据采集
Applications Manager(又称opManager)就是通过这种方式实现的。
使用这种方式,所监控Tomcat必须运行manager应用,缺省情况下,该应用总是运行在服务器中的。
增加manager角色用户
访问manager应用的用户的角色权限必须是 manager.
修改<TOMCAT_HOME>/conf目录下的tomcat-users.xml文件,在<tomcat-users>节点下添加一个user节点,即可创建一个用户。
Tomcat版本不同配置也有差异,5.x和6.x创建的用户角色应为manager,7.x创建的用户角色为manager-jmx,举例如下:
1、在5.x和6.x中创建一个manager角色的用户,用户名为admin,密码为chenfeng:
<user username="admin" password="chenfeng" roles="manager"/>
2、在7.x中创建一个manager角色的用户,用户名为admin,密码为chenfeng:
<user username="admin" password="chenfeng" roles="manager-jmx,manager-script,manager-status"/>
修改配置后,需要重新启动 Tomcat 服务器。
连接manager时将用户名/密码指定为admin/chenfeng
通过浏览器访问JMX Proxy Servlet
详见官方说明文档:
http://tomcat.apache.org/tomcat-6.0-doc/manager-howto.html#Using_the_JMX_Proxy_Servlet
What is JMX Proxy Servlet
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;/** * 使用JMX监控Tomcat示例 * * @author 陳峰 */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));// heapfor (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 MBeansSystem.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();}}