gpt4 book ai didi

java - 同步读取(即 "receive"而不是监听器)

转载 作者:行者123 更新时间:2023-12-02 00:06:10 25 4
gpt4 key购买 nike

以下代码片段(独立 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 中同步执行某些操作。有任何想法吗?没有找到任何提示为什么同步读取不应该在这里工作。在这种情况下,使用消息监听器并不是最佳选择,因为有时我必须使用不同的过滤器读取两条消息。

最佳答案

这是我接收消息的方式:

    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);
}

关于java - 同步读取(即 "receive"而不是监听器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13840552/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com