简体   繁体   English

ActiveMQ按需使用队列中的所有消息

[英]ActiveMQ Consume all messages from queue on demand

I have REST service which consumes message from queue. 我有REST服务,它消耗队列中的消息。 I want to consume message on demand - Give me all messages which are available in queue when rest service is getting called. 我想按需使用消息-给我所有在调用rest服务时队列中可用的消息。

I'm using ActiveMQ with Spring. 我在Spring上使用ActiveMQ。 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;
        }
    }

Always print exceptions. 始终打印例外。 This will help you debug. 这将帮助您调试。

Take a look at this - How to use Java JMS with MQseries 看一看- 如何将Java JMS与MQseries结合使用

When you use receive() method to receive message, the thread will block until the message becomes available or until the timeout value is exceeded. 当您使用receive()方法接收消息时,线程将阻塞,直到消息变为可用或超过超时值为止。 This can be found from the Javadoc of JmsTemplate : 可以从JmsTemplate的Javadoc中找到:

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 . 用于阻止的默认超时值为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. 这样,它不会阻塞,但是如果当前没有消息,它将立即终止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM