0

I have REST service which consumes message from queue. I want to consume message on demand - Give me all messages which are available in queue when rest service is getting called.

I'm using ActiveMQ with Spring. Below are the code which i'm using below code to get the message from queue. First time when i hit the service, i'm getting all the messages which are available in queue but if i further publish few more messages, even though if i'm not hitting service, message are getting subscribed. What could be the reason for this ?

while (true) {
        try {
            message = jmsTemplate.receive("TestQ");
            if (message instanceof TextMessage) {
                try {
                    System.out.println(((TextMessage)     message).getText());
                    msg = ((TextMessage) message).getText();
                } catch (JMSException ex) {
                    throw new RuntimeException(ex);
                }
            } else {
                throw new IllegalArgumentException("Message must be of type TextMessage");
            }

        } catch (Exception ex) {
            break;
        }
    }
Pankaj
  • 3,512
  • 16
  • 49
  • 83

2 Answers2

0

Always print exceptions. This will help you debug.

Take a look at this - How to use Java JMS with MQseries

Community
  • 1
  • 1
NRJ
  • 1,064
  • 3
  • 15
  • 32
0

When you use receive() method to receive message, the thread will block until the message becomes available or until the timeout value is exceeded. This can be found from the Javadoc of JmsTemplate:

This method should be used carefully, since it will block the thread until the message becomes available or until the timeout value is exceeded.

The default timeout value for blocking is RECEIVE_TIMEOUT_INDEFINITE_WAIT. So even though you're not hitting the service, your last session thread will block because of this indefinite wait time. To change the default timeout value, you can set the receive timeout to be

jmsTemplate.setReceiveTimeout(RECEIVE_TIMEOUT_NO_WAIT);

This way it will not block but will immediately terminate if currently there is no message.

tonga
  • 11,749
  • 25
  • 75
  • 96