我有一群tomcats,它们使用来自ActiveMQ主题的消息。现在,如果集群中的一个tomcat出现问题,那么我猜测消费者的数量会下降1个。
现在,我想在该主题上使用一些回调或监听器来检测该更改。那可行吗?
类似的地方:Region.getDestinations(ActiveMQDestination)有效吗?
答案 0 :(得分:2)
咨询消息是您所需要的。
每次收到包含此代码的消息时,这意味着消费者开始或停止。
doc http://activemq.apache.org/advisory-message.html
示例:
for (String string : bindvar) {
System.out.println(template.replace("$" + string + "$", getQueueLog(string)));
}
每次收到包含此代码的消息时,这意味着连接已启动或停止。
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Queue;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.ActiveMQSession;
import org.apache.activemq.command.ActiveMQMessage;
import org.apache.activemq.command.ConsumerInfo;
import org.apache.activemq.command.RemoveInfo;
public class AdvisorySupportConsumerAdvisoryTopic {
public static void main(String[] args) throws JMSException {
Connection conn = null;
try {
ConnectionFactory cf = new ActiveMQConnectionFactory("auto://localhost:5671");
conn = cf.createConnection("admin", "admin");
ActiveMQSession session = (ActiveMQSession) conn.createSession(false,
ActiveMQSession.INDIVIDUAL_ACKNOWLEDGE);
conn.start();
Queue q = session.createQueue("Q");
Destination advisoryDestination = org.apache.activemq.advisory.AdvisorySupport.getConsumerAdvisoryTopic(q);
MessageConsumer consumer = session.createConsumer(advisoryDestination);
consumer.setMessageListener(new MessageListener() {
@Override
public void onMessage(Message msg) {
if (msg instanceof ActiveMQMessage) {
try {
ActiveMQMessage aMsg = (ActiveMQMessage) msg;
System.out.println(aMsg.getStringProperty("consumerCount"));
System.out.println(aMsg.getStringProperty("producerCount"));
if (aMsg.getDataStructure() instanceof ConsumerInfo) {
// Consumer start
ConsumerInfo consumerInfo = (ConsumerInfo) aMsg.getDataStructure();
System.out.println(consumerInfo);
} else if (aMsg.getDataStructure() instanceof RemoveInfo) {
// Consumer stop
RemoveInfo removeInfo = (RemoveInfo) aMsg.getDataStructure();
System.out.println(removeInfo);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
try {
conn.close();
} catch (Exception e) {
}
}
}
}
}