JMS队列接收导致应用程序崩溃

时间:2017-02-14 15:36:26

标签: java glassfish jms

我创建了一个非常简单的JMS Queue示例来发送和接收消息。我将它设置为在发送一定数量后接收消息,然后对它们进行处理。收到所有消息后,尝试发送更多消息会导致应用程序崩溃。

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.jms.*;

@Startup
@Singleton
public class JMSQueue {
    /** SLF4J logger. */
    @SuppressWarnings("unused")
    private final Logger log = LoggerFactory.getLogger(JMSQueue.class);

    @Resource(mappedName = "jms/__defaultQueue")
    private Queue queue;

    @Resource(mappedName = "jms/__defaultQueueConnectionFactory")
    private QueueConnectionFactory factory;

    private int count = 0;

    private QueueConnection connection;
    private QueueSession session;
    private MessageProducer producer;
    private QueueReceiver receiver;

    public void init(){
        try {
            connection = factory.createQueueConnection();
            session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);

            producer = session.createProducer(queue);
            receiver = session.createReceiver(queue);
            connection.start();
        } catch (JMSException e) {
            log.error("JMS Queue Initialization failed.", e);
        }
    }

    public void sendMessage() throws JMSException {
        String messageBody = "ping" + count;
        Message request = session.createTextMessage(messageBody);
        request.setJMSReplyTo(queue);
        producer.send(request);
        count++;
        if (count >= 10) {
            count = 0;
            Message response = receiver.receive();
            while (response != null){
                String responseBody = ((TextMessage) response).getText();
                log.debug("jms - " + responseBody);
                try {
                    response = receiver.receive();
                } catch(JMSException e){
                    response = null;
                }
            }
        }
    }
}

我运行init一次创建连接,生成器和接收器,然后运行sendMessage 10次。在第十次它吐出所有十个收到的消息的输出。如果我之后多次点击sendMessage,我的应用程序崩溃了。我尝试更改它以创建和关闭每个没有任何改变的消息之后的连接。我正在运行glassfish应用程序Web服务器并尝试使用该队列来通知用户尝试访问的每个休息呼叫。

1 个答案:

答案 0 :(得分:0)

原来问题是由于没有超时,接收无限期地挂起。添加1毫秒的超时解决了这个问题。