ActiveMQ检测新的消费者主题

时间:2016-10-05 15:07:50

标签: java activemq broker

我有一个标准的activeMQ Broker

    private static String localVMurl = "vm://localhost";

    broker = new BrokerService();
    broker.addConnector(localVMurl); 
    broker.start();

一切都很好。我的目标是消费者使用特定主题连接到代理。一旦此连接 detectd ,如果生产者正在主动生成该主题,则代理将传递消息,或者代理将为该特定主题启动新的生产者。但是,要做到这一点,我需要有人检测新消费者何时连接并请求特定主题。

我的基本消费者代码:

    ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(remoterURL);
    Connection connection = connectionFactory.createConnection();
    connection.setClientID("clinet1");
    connection.start();

    session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Topic topic = session.createTopic("some_topic");
    MessageConsumer consumer = session.createConsumer(topic);
    consumer.setMessageListener(new MyMessageListener());

我可以在Broker日志中看到:

  <161005 11:03:41> [.0.1:64433@5001] DEBUG tRegion - localhost adding destination: topic://ActiveMQ.Advisory.Consumer.Topic.some_topic

所以我知道消费者连接,并订阅这个主题,我只需要以某种方式捕获该事件。

有关如何做到这一点的想法吗?

1 个答案:

答案 0 :(得分:1)

咨询消息是您所需要的。每次收到包含此代码的消息时,这意味着您有新的消费者开始或停止。

doc http://activemq.apache.org/advisory-message.html

示例:

    //org.apache.activemq.advisory.AdvisorySupport.getDestinationAdvisoryTopic(Destination)
Destination advisoryDestination = AdvisorySupport.getConsumerAdvisoryTopic(topic )
MessageConsumer consumer = session.createConsumer(advisoryDestination);
consumer.setMessageListener(this);

public void onMessage(Message msg){
    if (msg instanceof ActiveMQMessage){
        try {
            ActiveMQMessage aMsg =  (ActiveMQMessage)msg;
            ConsumerInfo consumer = (ConsumerInfo) aMsg.getDataStructure();
        } catch (JMSException e) {
            log.error("Failed to process message: " + msg);
        }
    }
}