当前位置:   article > 正文

java利用ManagementFactory获取tomcat的一些信息_如果通过java代码获取tomcat的连接使用情况

如果通过java代码获取tomcat的连接使用情况

         在上一篇中已经得到了jvm,os的一些信息,那如果是web项目,它在web容器中运行,那是否可以也得到一些信息进行监控呢?本篇写了个小例子,在tomcat6,jdk6下跑,利用ManagementFactory来获取tomcat的一些信息,至于其他web容器的获取请求,暂没做实验。。。


用jconsole监控,看看


      在catalina下,发现有很多信息。。。比如上图右侧圈出的,我们可以得到http-80这端口,也就是浏览器访问,可以得到总共有多少个请求访问过,接收了多少字节,发送了多少字节等信息。。。

下面贴个小例子源码

TestMonitorServlet.java

  1. package com.fei.monitor;
  2. import java.io.IOException;
  3. import java.io.PrintWriter;
  4. import javax.servlet.ServletException;
  5. import javax.servlet.http.HttpServlet;
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;
  8. /**
  9. * 测试监控
  10. * @author weijianfei
  11. *
  12. */
  13. public class TestMonitorServlet extends HttpServlet {
  14. private static final long serialVersionUID = 1L;
  15. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  16. this.doPost(request, response);
  17. }
  18. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  19. StringBuffer sb = new StringBuffer();
  20. sb.append("<h3>========tomcatInfo========</h3><br/>");
  21. for(TomcatInformations info : TomcatInformations.buildTomcatInformationsList()){
  22. sb.append(info).append("<br/><br/>");
  23. }
  24. sb.append("<br/><br/>");
  25. sb.append("<h3>========threadInfo====</h3><br/>");
  26. for(ThreadInformations t : ThreadInformations.buildThreadInformationsList()){
  27. sb.append(t).append("<br/><br/>");
  28. }
  29. //输出
  30. outToClient(response, sb.toString());
  31. }
  32. private void outToClient(HttpServletResponse response,String content){
  33. response.setContentType("text/html");
  34. response.setCharacterEncoding("utf-8");
  35. PrintWriter writer;
  36. try {
  37. writer = response.getWriter();
  38. writer.write(content);
  39. writer.flush();
  40. writer.close();
  41. } catch (IOException e) {
  42. e.printStackTrace();
  43. }
  44. }
  45. }

MBeans.java

  1. package com.fei.monitor;
  2. import java.lang.management.ManagementFactory;
  3. import java.util.Set;
  4. import javax.management.JMException;
  5. import javax.management.MBeanServer;
  6. import javax.management.MalformedObjectNameException;
  7. import javax.management.ObjectName;
  8. public class MBeans {
  9. private final MBeanServer mbeanServer;
  10. MBeans() {
  11. this(getPlatformMBeanServer());
  12. }
  13. private MBeans(MBeanServer mbeanServer) {
  14. super();
  15. this.mbeanServer = mbeanServer;
  16. }
  17. /**
  18. * 获取MBeanServer
  19. * @return
  20. */
  21. static MBeanServer getPlatformMBeanServer() {
  22. return ManagementFactory.getPlatformMBeanServer();
  23. }
  24. /**
  25. * 获取tomcat的线程池
  26. * @return
  27. * @throws MalformedObjectNameException
  28. */
  29. Set<ObjectName> getTomcatThreadPools() throws MalformedObjectNameException {
  30. return mbeanServer.queryNames(new ObjectName("*:type=ThreadPool,*"), null);
  31. }
  32. Set<ObjectName> getTomcatGlobalRequestProcessors() throws MalformedObjectNameException {
  33. return mbeanServer.queryNames(new ObjectName("*:type=GlobalRequestProcessor,*"), null);
  34. }
  35. Object getAttribute(ObjectName name, String attribute) throws JMException {
  36. return mbeanServer.getAttribute(name, attribute);
  37. }
  38. }
</pre><pre name="code" class="java">


  1. package com.fei.monitor;
  2. import java.lang.management.ManagementFactory;
  3. import java.lang.management.RuntimeMXBean;
  4. final public class PID {
  5. /**
  6. * 获取当前进程id
  7. * @return
  8. */
  9. public static String getPID(){
  10. final RuntimeMXBean rtb = ManagementFactory.getRuntimeMXBean();
  11. //pid@host
  12. return rtb.getName().split("@")[0];
  13. }
  14. }



TomcatInformations.java

  1. package com.fei.monitor;
  2. import java.io.Serializable;
  3. import java.util.ArrayList;
  4. import java.util.Collections;
  5. import java.util.List;
  6. import javax.management.AttributeNotFoundException;
  7. import javax.management.InstanceNotFoundException;
  8. import javax.management.JMException;
  9. import javax.management.MalformedObjectNameException;
  10. import javax.management.ObjectName;
  11. final class TomcatInformations implements Serializable {
  12. private static final boolean TOMCAT_USED = System.getProperty("catalina.home") != null;
  13. private static final long serialVersionUID = -6145865427461051370L;
  14. @SuppressWarnings("all")
  15. private static final List<ObjectName> THREAD_POOLS = new ArrayList<ObjectName>();
  16. @SuppressWarnings("all")
  17. private static final List<ObjectName> GLOBAL_REQUEST_PROCESSORS = new ArrayList<ObjectName>();
  18. private final String name;
  19. private final int maxThreads;
  20. private final int currentThreadCount;
  21. private final int currentThreadsBusy;
  22. private final long bytesReceived;
  23. private final long bytesSent;
  24. private final int requestCount;
  25. private final int errorCount;
  26. private final long processingTime;
  27. private final long maxTime;
  28. private TomcatInformations(MBeans mBeans, ObjectName threadPool) throws JMException {
  29. super();
  30. name = threadPool.getKeyProperty("name");
  31. maxThreads = (Integer) mBeans.getAttribute(threadPool, "maxThreads");
  32. currentThreadCount = (Integer) mBeans.getAttribute(threadPool, "currentThreadCount");
  33. currentThreadsBusy = (Integer) mBeans.getAttribute(threadPool, "currentThreadsBusy");
  34. ObjectName grp = null;
  35. for (final ObjectName globalRequestProcessor : GLOBAL_REQUEST_PROCESSORS) {
  36. if (name.equals(globalRequestProcessor.getKeyProperty("name"))) {
  37. grp = globalRequestProcessor;
  38. break;
  39. }
  40. }
  41. if (grp != null) {
  42. bytesReceived = (Long) mBeans.getAttribute(grp, "bytesReceived");
  43. bytesSent = (Long) mBeans.getAttribute(grp, "bytesSent");
  44. requestCount = (Integer) mBeans.getAttribute(grp, "requestCount");
  45. errorCount = (Integer) mBeans.getAttribute(grp, "errorCount");
  46. processingTime = (Long) mBeans.getAttribute(grp, "processingTime");
  47. maxTime = (Long) mBeans.getAttribute(grp, "maxTime");
  48. } else {
  49. bytesReceived = 0;
  50. bytesSent = 0;
  51. requestCount = 0;
  52. errorCount = 0;
  53. processingTime = 0;
  54. maxTime = 0;
  55. }
  56. }
  57. public static List<TomcatInformations> buildTomcatInformationsList() {
  58. if (!TOMCAT_USED) {
  59. return Collections.emptyList();
  60. }
  61. try {
  62. synchronized (THREAD_POOLS) {
  63. if (THREAD_POOLS.isEmpty() || GLOBAL_REQUEST_PROCESSORS.isEmpty()) {
  64. initMBeans();
  65. }
  66. }
  67. final MBeans mBeans = new MBeans();
  68. final List<TomcatInformations> tomcatInformationsList = new ArrayList<TomcatInformations>(
  69. THREAD_POOLS.size());
  70. for (final ObjectName threadPool : THREAD_POOLS) {
  71. tomcatInformationsList.add(new TomcatInformations(mBeans, threadPool));
  72. }
  73. return tomcatInformationsList;
  74. } catch (final InstanceNotFoundException e) {
  75. return Collections.emptyList();
  76. } catch (final AttributeNotFoundException e) {
  77. return Collections.emptyList();
  78. } catch (final JMException e) {
  79. throw new IllegalStateException(e);
  80. }
  81. }
  82. private static void initMBeans() throws MalformedObjectNameException {
  83. final MBeans mBeans = new MBeans();
  84. THREAD_POOLS.clear();
  85. GLOBAL_REQUEST_PROCESSORS.clear();
  86. THREAD_POOLS.addAll(mBeans.getTomcatThreadPools());
  87. GLOBAL_REQUEST_PROCESSORS.addAll(mBeans.getTomcatGlobalRequestProcessors());
  88. }
  89. String getName() {
  90. return name;
  91. }
  92. int getMaxThreads() {
  93. return maxThreads;
  94. }
  95. int getCurrentThreadCount() {
  96. return currentThreadCount;
  97. }
  98. int getCurrentThreadsBusy() {
  99. return currentThreadsBusy;
  100. }
  101. long getBytesReceived() {
  102. return bytesReceived;
  103. }
  104. long getBytesSent() {
  105. return bytesSent;
  106. }
  107. int getRequestCount() {
  108. return requestCount;
  109. }
  110. int getErrorCount() {
  111. return errorCount;
  112. }
  113. long getProcessingTime() {
  114. return processingTime;
  115. }
  116. long getMaxTime() {
  117. return maxTime;
  118. }
  119. /** {@inheritDoc} */
  120. @Override
  121. public String toString() {
  122. return getClass().getSimpleName() + "[端口名name=" + getName() + ", 最大线程数maxThreads="
  123. + getMaxThreads() + ",当前线程数 currentThreadCount=" + getCurrentThreadCount()
  124. + ", 当前活动线程数currentThreadsBusy=" + getCurrentThreadsBusy() + ",接收字节数 bytesReceived="
  125. + getBytesReceived() + ",发送字节数 bytesSent=" + getBytesSent() + ",请求数 requestCount="
  126. + getRequestCount() + ", 错误数errorCount=" + getErrorCount() + ", 处理时间processingTime="
  127. + getProcessingTime() + ", 最大处理时间maxTime=" + getMaxTime() + ']';
  128. }
  129. }

ThreadInformations.java

  1. package com.fei.monitor;
  2. import java.io.Serializable;
  3. import java.lang.management.ManagementFactory;
  4. import java.lang.management.ThreadMXBean;
  5. import java.net.InetAddress;
  6. import java.net.UnknownHostException;
  7. import java.util.ArrayList;
  8. import java.util.Arrays;
  9. import java.util.Collections;
  10. import java.util.List;
  11. import java.util.Map;
  12. class ThreadInformations implements Serializable {
  13. private static final long serialVersionUID = 3604281253550723654L;
  14. private final String name;//线程名称
  15. private final long id;//线程id
  16. private final int priority;//线程有限度
  17. private final boolean daemon;//是不是守护线程
  18. private final Thread.State state;//线程状态
  19. private final long cpuTimeMillis;//返回指定 ID 的线程的总 CPU 时间
  20. private final long userTimeMillis;//返回指定 ID 的线程在用户模式中执行的 CPU 时间
  21. private final boolean deadlocked;//是否死锁
  22. private final String globalThreadId;//全局线程id名称
  23. private final List<StackTraceElement> stackTrace;
  24. private ThreadInformations(Thread thread, List<StackTraceElement> stackTrace, long cpuTimeMillis,
  25. long userTimeMillis, boolean deadlocked, String hostAddress) {
  26. super();
  27. this.name = thread.getName();
  28. this.id = thread.getId();
  29. this.priority = thread.getPriority();
  30. this.daemon = thread.isDaemon();
  31. this.state = thread.getState();
  32. this.stackTrace = stackTrace;
  33. this.cpuTimeMillis = cpuTimeMillis;
  34. this.userTimeMillis = userTimeMillis;
  35. this.deadlocked = deadlocked;
  36. this.globalThreadId = buildGlobalThreadId(thread, hostAddress);
  37. }
  38. public static List<ThreadInformations> buildThreadInformationsList() {
  39. final ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
  40. final Map<Thread, StackTraceElement[]> stackTraces = Thread.getAllStackTraces();
  41. final List<Thread> threads = new ArrayList<Thread>(stackTraces.keySet());
  42. //虚拟机是否允许测量所有线程的cup时间
  43. //isThreadCpuTimeSupported() 方法可用于确定 Java 虚拟机是否支持测量任何线程的 CPU 时间。
  44. //isCurrentThreadCpuTimeSupported() 方法可用于确定 Java 虚拟机是否支持测量当前线程的 CPU 时间。
  45. //支持任何线程 CPU 时间测量的 Java 虚拟机实现也支持当前线程的 CPU 时间测量
  46. final boolean cpuTimeEnabled = threadBean.isThreadCpuTimeSupported() && threadBean.isThreadCpuTimeEnabled();
  47. //获取所有死锁线程的id
  48. final long[] deadlockedThreads = getDeadlockedThreads(threadBean);
  49. final List<ThreadInformations> threadInfosList = new ArrayList<ThreadInformations>(threads.size());
  50. String hostAddress;
  51. try {
  52. hostAddress = InetAddress.getLocalHost().getHostAddress();
  53. } catch (UnknownHostException e) {
  54. hostAddress = "unknown";
  55. }
  56. for (final Thread thread : threads) {
  57. final StackTraceElement[] stackTraceElements = stackTraces.get(thread);
  58. final List<StackTraceElement> stackTraceElementList = stackTraceElements == null ? null
  59. : new ArrayList<StackTraceElement>(Arrays.asList(stackTraceElements));
  60. final long cpuTimeMillis;//返回指定 ID 的线程的总 CPU 时间(以毫微秒为单位)。
  61. final long userTimeMillis;//返回指定 ID 的线程在用户模式中执行的 CPU 时间(以毫微秒为单位)。
  62. if (cpuTimeEnabled) {
  63. cpuTimeMillis = threadBean.getThreadCpuTime(thread.getId()) / 1000000;
  64. userTimeMillis = threadBean.getThreadUserTime(thread.getId()) / 1000000;
  65. } else {
  66. cpuTimeMillis = -1;
  67. userTimeMillis = -1;
  68. }
  69. final boolean deadlocked = deadlockedThreads != null
  70. && Arrays.binarySearch(deadlockedThreads, thread.getId()) >= 0;
  71. threadInfosList.add(new ThreadInformations(thread, stackTraceElementList,
  72. cpuTimeMillis, userTimeMillis, deadlocked, hostAddress));
  73. }
  74. return threadInfosList;
  75. }
  76. /**
  77. * 获取所有的死锁线程id
  78. * @param threadBean
  79. * @return
  80. */
  81. private static long[] getDeadlockedThreads(ThreadMXBean threadBean) {
  82. final long[] deadlockedThreads;
  83. //这方法是jdk1.6才提供的,简单点,在这就不做检查了,
  84. if (threadBean.isSynchronizerUsageSupported()) {
  85. deadlockedThreads = threadBean.findDeadlockedThreads();
  86. } else {
  87. deadlockedThreads = threadBean.findMonitorDeadlockedThreads();
  88. }
  89. if (deadlockedThreads != null) {
  90. Arrays.sort(deadlockedThreads);
  91. }
  92. return deadlockedThreads;
  93. }
  94. String getName() {
  95. return name;
  96. }
  97. long getId() {
  98. return id;
  99. }
  100. int getPriority() {
  101. return priority;
  102. }
  103. boolean isDaemon() {
  104. return daemon;
  105. }
  106. Thread.State getState() {
  107. return state;
  108. }
  109. List<StackTraceElement> getStackTrace() {
  110. if (stackTrace != null) {
  111. return Collections.unmodifiableList(stackTrace);
  112. }
  113. return stackTrace;
  114. }
  115. String getExecutedMethod() {
  116. final List<StackTraceElement> trace = stackTrace;
  117. if (trace != null && !trace.isEmpty()) {
  118. return trace.get(0).toString();
  119. }
  120. return "";
  121. }
  122. long getCpuTimeMillis() {
  123. return cpuTimeMillis;
  124. }
  125. long getUserTimeMillis() {
  126. return userTimeMillis;
  127. }
  128. boolean isDeadlocked() {
  129. return deadlocked;
  130. }
  131. String getGlobalThreadId() {
  132. return globalThreadId;
  133. }
  134. private static String buildGlobalThreadId(Thread thread, String hostAddress) {
  135. return PID.getPID() + '_' + hostAddress + '_' + thread.getId();
  136. }
  137. /** {@inheritDoc} */
  138. @Override
  139. public String toString() {
  140. StringBuffer sb = new StringBuffer();
  141. sb.append("[线程id=" + getId()
  142. +",线程具体id(pid_host_tid)="+getGlobalThreadId()
  143. + ",线程名称 name=" + getName()
  144. + ", 是否是守护线程daemon="+ isDaemon()
  145. + ",线程优先度 priority=" + getPriority()
  146. + ",是不是死锁 deadlocked=" + isDeadlocked()
  147. + ", 运行状态state=" + getState()
  148. +",线程使用CPU时间(毫秒)="+getCpuTimeMillis()
  149. +",线程在用户模式下使用CPU时间(毫秒)="+getUserTimeMillis()
  150. +",执行的方法="+getExecutedMethod());
  151. if(getStackTrace() != null && !getStackTrace().isEmpty()){
  152. sb.append("<br/>栈信息:");
  153. for(StackTraceElement s : getStackTrace()){
  154. sb.append("<br/>").append(s.toString());
  155. }
  156. }
  157. sb.append( ']');
  158. return sb.toString();
  159. }
  160. }
  http://127.0.0.1/testweb/TestMonitorServlet访问,查看结果




源码下载


声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/319766
推荐阅读
相关标签
  

闽ICP备14008679号