# java监控Active MQ

1.修改activemq.xml

broker节点增加useJmx="true"属性

<broker xmlns="http://activemq.apache.org/schema/core" brokerName="localhost" dataDirectory="${activemq.data}" useJmx="true">
1

managementContext节点createConnector属性改为"true",增加connectorPort="11099"属性

<managementContext>
	<managementContext createConnector="true" connectorPort="11099"/>
</managementContext>
1
2
3

2.pom引入mq依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
1
2
3
4

3.代码实现

public static void main(String[] args) throws Exception {
        String host = "localhost";
        int port = 11099;
        //输入ActiveMQ的IP和JMX的端口
        String url = "service:jmx:rmi:///jndi/rmi://" + host + ":" + port + "/jmxrmi";
        JMXServiceURL urls = new JMXServiceURL(url);
        JMXConnector connector = JMXConnectorFactory.connect(urls, null);
        connector.connect();
        MBeanServerConnection conn = connector.getMBeanServerConnection();
        //这里的brokerName=localhost是指当前ActiveMQ的节点名称,在配置文件activemq.xml中
        ObjectName name = new ObjectName("org.apache.activemq:brokerName=localhost,type=Broker");
        BrokerViewMBean mBean = (BrokerViewMBean) MBeanServerInvocationHandler.newProxyInstance(conn, name, BrokerViewMBean.class, true);
        //获取点对点的队列       mBean.getTopics() 获取订阅模式的队列
        for (ObjectName na : mBean.getQueues()) {
            QueueViewMBean queueBean = (QueueViewMBean)
                    MBeanServerInvocationHandler.newProxyInstance(conn, na, QueueViewMBean.class, true);
            LocalDateTime time = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss");
            System.out.println("****************" + formatter.format(time) + "**************");
            System.out.println("队列的名称:" + queueBean.getName());
            System.out.println("队列中剩余的消息数:" + queueBean.getQueueSize());
            System.out.println("消费者数:" + queueBean.getConsumerCount());
            System.out.println("出队列的数量:" + queueBean.getDequeueCount());
        }
        connector.close();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26