0

以下代码片段(独立的 Java 应用程序)永远不会在队列中找到任何消息,而使用消息侦听器实现的同一个客户端(使用 Glassfish 3.1)会:

ctx = new InitialContext();
connectionFactory = (ConnectionFactory) ctx.lookup("foo.Factory");

partsQueue = (Queue) ctx.lookup("foo.PartsQueue");

conn = connectionFactory.createConnection();
session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
consumer = session.createConsumer(partsQueue);

conn.start();

Message msg = null;
int cnt = -1;
do {
    cnt++;
    msg = consumer.receiveNoWait();
} while (msg != null);

        System.out.println("cnt: " + cnt);

如果我在创建消费者后使用以下代码,监听器将找到消息并成功消费它们:

listener = new AssemblerListener(this);
consumer.setMessageListener(listener);
System.out.println("waiting for msgs...");
conn.start();

如前所述,独立的 Java 客户端,我不想在 MDB 中同步做某事。有任何想法吗?没有找到任何提示为什么同步读取在这里不起作用。在这种情况下,使用消息侦听器不是最佳选择,因为有时我必须使用不同的过滤器读取两条消息。

4

2 回答 2

3

这是我接收消息的方式:

    ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(url);

    // Getting JMS connection from the server
    ConnectionFactory connectionFactory= activeMQConnectionFactory;

    Connection connection = connectionFactory.createConnection();

    // Creating session for sending messages
    Session session = connection.createSession(false,Session.CLIENT_ACKNOWLEDGE);


    // Getting the queue 'TESTQUEUE'
    Destination destination = session.createQueue("queue_name");

    // MessageConsumer is used for receiving (consuming) messages

    MessageConsumer consumer = session.createConsumer(destination);

    connection.start();        

    // Here we receive the message.
    // By default this call is blocking, which means it will wait
    // for a message to arrive on the queue.
    Message message= consumer.receive(500);
    while(message!= null)
    {

        // There are many types of Message and TextMessage
        // is just one of them. Producer sent us a TextMessage
        // so we must cast to it to get access to its .getText()
        // method.
        if (message instanceof TextMessage) 
        {
            TextMessage textMessage = (TextMessage) message;
       //     BytesMessage Byte

            System.out.println("Received message '"+ textMessage.getText() + "'");
        }           
        message = consumer.receive(1);
      }
于 2012-12-12T13:34:52.693 回答
0

consumer.receiveNoWait()null如果当时队列是空的,则返回。如果它为空,您的代码不会再次尝试接收消息。

您应该继续循环或使用consumer.receive()which 将阻塞直到消息可用

于 2012-12-12T13:29:39.403 回答