we can use JMX to monitor our ActiveMQ ,first config the configuration of activemq
<broker xmlns="http://activemq.apache.org/schema/core" useJmx="true" brokerName="localhost" dataDirectory="${activemq.base}/data">
<managementContext>
<managementContext connectorPort="2011"/><!-- jmxDomainName="my-broker"/>-->
</managementContext>
<!-- The transport connectors ActiveMQ will listen to -->
<transportConnectors>
<transportConnector name="openwire" uri="tcp://localhost:61616" />
</transportConnectors>
</broker>
the jmsDomainName means The JMX domain name , and the default values if org.apache.activemq
then we can coding start our activemq using this configuration , type in the console:
activemq start xbean:/the/configuration/path
and in the console we can see :
INFO | JMX consoles can connect to service:jmx:rmi:///jndi/rmi://localhost:2011/jmxrmi
then coding like this:
public static void main(String[] args) throws Exception {
JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:2011/jmxrmi");
JMXConnector connector = JMXConnectorFactory.connect(url, null);
connector.connect();
MBeanServerConnection connection = connector.getMBeanServerConnection();
ObjectName name = new ObjectName(
// "my-broker:BrokerName=localhost,Type=Broker");
"org.apache.activemq:brokerName=localhost,type=Broker");
BrokerViewMBean mbean = (BrokerViewMBean) MBeanServerInvocationHandler
.newProxyInstance(connection, name, BrokerViewMBean.class, true);
System.out.println("Statistics for broker " + mbean.getBrokerId() + " - " + mbean.getBrokerName());
System.out.println("\n-----------------\n");
System.out.println("Total message count: " + mbean.getTotalMessageCount() + "\n");
System.out.println("Total number of consumers: " + mbean.getTotalConsumerCount());
System.out.println("Total number of Queues: " + mbean.getQueues().length);
for (ObjectName queueName : mbean.getQueues()) {
System.out.println(queueName);
QueueViewMBean queueMbean = (QueueViewMBean) MBeanServerInvocationHandler
.newProxyInstance(connection, queueName,
QueueViewMBean.class, true);
System.out.println("\n-----------------\n");
System.out.println("Statistics for queue " + queueMbean.getName());
System.out.println("Size: " + queueMbean.getQueueSize());
System.out.println("Number of consumers: " + queueMbean.getConsumerCount());
}
}
Although, in many books ,they make the first letter of brokerName and Type as upper case, in fact ,
we should make the first letter of brokerName and Type as lower case, otherwise, it will throw an
exception like this:
javax.management.InstanceNotFoundException: org.apache.activemq:BrokerName=localhost,Type=Broker