I'm using ActiveMQ. My consumer code is called from a main method. Once the main class terminates, I expect JMSMessageListener to have been registered on the queue and whenever there is a message on "TestTopic", onMessage to be called, which is not happening.

//JMS Consumer
public class JMSConsumer {
    public void consume() {
        String url = "tcp://localhost:61616";
        ConnectionFactory factory = new ActiveMQConnectionFactory(url);
        try {
            Connection connection = factory.createConnection();
            Session session = connection.createSession(false,
                Session.AUTO_ACKNOWLEDGE);
            Topic topic = session.createTopic("TestTopic");
            MessageConsumer consumer = session.createConsumer(topic);
            JMSMessageListener listener = new JMSMessageListener();
            consumer.setMessageListener(listener);
            connection.start();
        } catch (JMSException exp) {}
    }
}

//JMS Message Listener
public class JMSMessageListener implements MessageListener {
    @Override
    public void onMessage(javax.jms.Message msg) {
        System.out.println(msg.toString());
    }
}

Is this because the main thread has been terminated and the listener is not live anymore? I thought with setMessageListener, the above code should internally create a thread that should always be running.

有帮助吗?

解决方案

Is this because the main thread has been terminated and the listener is not live anymore? I thought with setMessageListener, the above code should internally create a thread that should always be running.

setMessageListener does not create a new thread. When you create a new Session from the Connection, a new thread is created. So yes even if the main thread terminates, the Session thread should continue running.

Your code looks correct to me. Are you sure that messages exist on that topic? Also only messages published to the topic after the consumer comes live will be received.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top