监视JDBC连接

时间:2012-12-27 08:39:55

标签: tomcat jdbc jmx

我正在尝试使用JMX监视tomcat中的JDBC连接。

但它仅提供有关数据源资源的信息,我想要在Database.properties文件中定义连接状态。

有没有办法获得他们的身份?

2 个答案:

答案 0 :(得分:4)

您要求的不仅仅是JNDI DataSource信息(例如忙线程和空闲线程)。

我强烈推荐这个资源用于基于JMX的监控:

http://wiki.apache.org/tomcat/FAQ/Monitoring

答案 1 :(得分:4)

使用此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>");
    }
}