Getting a queue size of an ActiveMQ queue using MBean (Spring JMX).
Spring Config file
* Running the Queue Counter
Spring Config file
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean class="org.springframework.jmx.support.MBeanServerConnectionFactoryBean" id="mbeanServerConnection"> <property name="serviceUrl" value="service:jmx:rmi:///jndi/rmi://localhost:1099/jmxrmi"> </property></bean> <bean class="com.sample.QueueSizeCounter" id="queueCounter"> <property name="mBeanServerConnection" ref="mbeanServerConnection"> </property></bean> </beans>* A class using the MBeanServerConnection to fetch the attribute from the MBean
package com.sample;
import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import org.apache.log4j.Logger;
public class QueueSizeCounter {
private MBeanServerConnection mBeanServerConnection;
private Logger logger = Logger.getLogger(QueueSizeCounter.class);
public Long getQueueSize(String queueName) {
Long queueSize = null;
try {
ObjectName objectNameRequest = new ObjectName(
"org.apache.activemq:BrokerName=localhost,Type=Queue,Destination=" + queueName);
queueSize = (Long) mBeanServerConnection.getAttribute(objectNameRequest, "QueueSize");
return queueSize;
}
catch (Exception e) {
logger.error(e.getMessage());
}
return queueSize;
}
public void setmBeanServerConnection(MBeanServerConnection mBeanServerConnection) {
this.mBeanServerConnection = mBeanServerConnection;
}
}
* Running the Queue Counter
package com.sample;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
QueueSizeCounter queueCounter = (QueueSizeCounter) ctx.getBean("queueCounter");
String queueName = "Queue1";
long queueSize = queueCounter.getQueueSize(queueName);
System.out.println("Size of " + queueName + " : " + queueSize);
}
}
2 comments:
Hi Sachin. Thanks for the posting. I tried it your code, but getting some exception connecting to the broker.
I was wondering if you do some configuration, other that adding useJmx="true" in your activemq.xml file.
I have this config:
<broker xmlns="http://activemq.apache.org/schema/core" useJmx="true" brokerName="localhost"
Thanks!
There was no change except the useJmx="true" setting.
Can you post the exception you'r getting...
Post a Comment