最近开始学习activemq系统的使用,关于如何在activemq中时实获取一个主题/队列(topic/queue)的订阅/消费者数量,让我花了挺多时间才搞明白:
在activemq中,可以通过订阅主题或队列对应的消息管理主题,从而获取咨询消息(Advisory Message),
每当新增/减少订阅者时都会收到相关的咨询消息。
Advisory Message中就包含了一些我们想要的数据(包含在consumerCount
属性中)。
关于Advisory Message的详细说明参见官方文档: http://activemq.apache.org/advisory-message.html
废话少说,上代码,下面的代码完整说明了如何从Advisory Message获取consumerCount
属性得到消费者数量.
以下为JUNIT 测试代码:
import javax.jms.Connection;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.advisory.AdvisorySupport;
import org.apache.activemq.command.ActiveMQTopic;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TestAdvisory {
private static final Logger logger = LoggerFactory.getLogger(TestAdvisory.class);
@Test
public void test() {
// 创建连接本地activemq的ActiveMQConnectionFactory实例
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory();
Connection connection = null;
try {
connection = connectionFactory.createConnection();
connection.start();
Session session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);
// 创建 advisory topic : ActiveMQ.Advisory.Consumer.Topic.chat1,用于监控topic消费者的状态变化
ActiveMQTopic advisoryTopic = AdvisorySupport.getConsumerAdvisoryTopic(new ActiveMQTopic("chat1"));
MessageConsumer consumer = session.createConsumer(advisoryTopic);
consumer.setMessageListener(new MessageListener() {
@Override
public void onMessage(Message message) {
try {
// 获取消费者数量属性
int consumerCount = message.getIntProperty("consumerCount");
logger.info("consumerCount = {} ",consumerCount);
} catch (JMSException e) {
e.printStackTrace();
}
}
});
Thread.sleep(20000);
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if(null != connection){
connection.close();
}
} catch (JMSException e) {
e.printStackTrace();
}
}
}
}