I recently felt the need for accessing the metrics / statistics of a JDBC Data Source from within an application that is deployed on a Oracle Weblogic Server. I did not succeed right away, so I document it here.
Basically we just need some calls to JMX. Using the Weblogic RuntimeServiceMBean
we navigate from ServerRuntime
and JDBCServiceRuntime
to JDBCDataSourceRuntimeMBeans
. From there we get ObjectName
s for each JDBC Data Source that we can access from our application. Using these object names we can retreive the metrics.
First we get the MBeanServer via JNDI:
- MBeanServer getMBeanServer() throws NamingException {
- InitialContext ctx = new InitialContext();
- MBeanServer server = (MBeanServer) ctx.lookup("java:comp/env/jmx/runtime");
- return server;
- }
Then we navigate as described before:
- ObjectName[] getJdbcDataSourceRuntimeMBeans(MBeanServer server)
- throws MalformedObjectNameException, AttributeNotFoundException, MBeanException,
- InstanceNotFoundException, ReflectionException {
- ObjectName service = new ObjectName(
- "com.bea:Name=RuntimeService,Type=weblogic.management.mbeanservers.runtime.RuntimeServiceMBean");
- ObjectName serverRT = (ObjectName) server.getAttribute(service, "ServerRuntime");
- ObjectName jdbcRT = (ObjectName) server.getAttribute(serverRT, "JDBCServiceRuntime");
- ObjectName[] dsRTs = (ObjectName[]) server.getAttribute(jdbcRT, "JDBCDataSourceRuntimeMBeans");
- return dsRTs;
- }
To get the current number of active connections and the current capacity of the connection pool, we access the attributes ActiveConnectionsCurrentCount
and CurrCapacity
:
- MBeanServer server = getMBeanServer();
- ObjectName[] dsRTs = getJdbcDataSourceRuntimeMBeans(server);
- for (ObjectName dsRT : dsRTs) {
- String name = (String) server.getAttribute(dsRT, "Name");
- Integer activeConnectionsCurrentCount =
- (Integer) server.getAttribute(dsRT, "ActiveConnectionsCurrentCount");
- Integer currCapacity =
- (Integer) server.getAttribute(dsRT, "CurrCapacity");
- // do something with these metrics
- }
There are a bunch of metrics. Here is a list. You can enumerate them using MBeanAttrbuteInfo
:
- /**
- * Returns MBean-Attribute Infos such as Name, Type and Description
- */
- public MBeanAttributeInfo[] getMetricsAttributeInfos() {
- try {
- MBeanServer server = getMBeanServer();
- ObjectName[] dsRTs = getJdbcDataSourceRuntimeMBeans(server);
- if (dsRTs.length>0) {
- return server.getMBeanInfo(dsRTs[0]).getAttributes();
- }
- } catch (Exception e) {
- // your favourite error logging mechanism here...
- }
- return new MBeanAttributeInfo[]{};
- }
every MBeanAttributeInfo
contains name, type and description of the attribute.
Note: I am using Weblogic Server 11g here. I have not tried this on WLS 12c.