2012-12-27 123 views
8

我想監視使用JMX的tomcat中的JDBC連接。監視JDBC連接

但它只給出關於數據源資源的信息,我想要在Database.properties文件中定義連接的狀態。

有什麼方法可以獲得他們的狀態?

+0

我只想要繁忙和空閒線程的數量不是等待或阻塞狀態。 – Rupinder

+0

什麼是'Database.properties'?它與Tomcat有什麼關係,這是什麼框架? – mindas

+0

嗨Rupinder,你終於找到了這樣一個實用程序? – JavaTec

回答

2

有了這個servlet 3.0例如,你可以監視所有org.apache.tomcat.jdbc.pool.jmx.ConnectionPool信息,包括空閒和活動連接。

import java.io.IOException; 
import java.io.PrintWriter; 
import java.lang.management.ManagementFactory; 
import java.util.Set; 
import javax.management.MBeanAttributeInfo; 
import javax.management.MBeanInfo; 
import javax.management.MBeanServer; 
import javax.management.ObjectName; 
import javax.servlet.ServletException; 
import javax.servlet.annotation.WebServlet; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
@WebServlet("/poolmonitor") 
public class HelloServlet extends HttpServlet { 
    private static final long serialVersionUID = 1L; 
    @Override 
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
      throws ServletException, IOException { 
     PrintWriter writer = resp.getWriter(); 
     writer.println("<!DOCTYPE html>"); 
     writer.println("<html>"); 
     writer.println("<body>"); 
     writer.println("<p><h1>Tomcat Pool</h1></p><p>"); 
     try { 
      MBeanServer server = ManagementFactory.getPlatformMBeanServer(); 
      Set<ObjectName> objectNames = server.queryNames(null, null); 
      for (ObjectName name : objectNames) { 
       MBeanInfo info = server.getMBeanInfo(name); 
       if (info.getClassName().equals(
         "org.apache.tomcat.jdbc.pool.jmx.ConnectionPool")) { 
        for (MBeanAttributeInfo mf : info.getAttributes()) { 
         Object attributeValue = server.getAttribute(name, 
           mf.getName()); 
         if (attributeValue != null) { 
          writer.println("" + mf.getName() + " : " 
            + attributeValue.toString() + "<br/>"); 

         } 
        } 
        break; 
       } 
      } 
     } catch (Exception e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     writer.println("</p></body>"); 
     writer.println("</html>"); 
    } 
}