跳到主要内容

同步或异步接收消息

消息消费者可以使用以下模式之一从目标接收消息:

  • 同步 — 消息消费者必须调用接收方法,明确地从目标获取消息。
  • 异步 — 消息监听器注册到消息消费者。当消息到达消息消费者时,通过调用监听器的 onMessage() 方法来传递消息。

同步接收

要同步接收消息,请从 MessageConsumer 类调用以下接收方法之一:

  • receive() 接收下一条消息;无限期阻塞。

  • receive(long timeout) 在指定的超时期间内接收下一条到达的消息。

  • receiveNoWait() 如果立即有消息可用,则接收下一条消息,但当没有消息可用时不等待。也就是说,当没有消息可用时,调用立即超时。

以下示例代码展示了如何同步接收消息:

ConnectionFactory cf = (ConnectionFactory)context.lookup("cf/default");
Topic topic = (Topic)context.lookup("topic/testDest");
connection = cf.createConnection();

// 创建会话,非事务性且自动确认
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

// 创建持久订阅者
String subscriptionName = new String("subscription");
subscriber = session.createDurableSubscriber(topic, subscriptionName);

connection.start();

// 阻塞调用接收,超时 1 秒
Message testMessage = subscriber.receive(1000);
if(testMessage != null) {
// 处理消息
}

connection.stop();

异步接收

要异步接收消息,您可以将 MessageListener 注册到 MessageConsumer

以下示例代码展示了如何异步接收消息:

ConnectionFactory cf = (ConnectionFactory)context.lookup("cf/default");
Topic topic = (Topic)context.lookup("topic/testDest");
connection = cf.createConnection();

// 创建会话,非事务性且自动确认
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

// 创建持久订阅者
String subscriptionName = new String("subscription");
subscriber = session.createDurableSubscriber(topic, subscriptionName);
jmsMessageListener myListener = new jmsMessageListener();
subscriber.setMessageListener(myListener);

connection.start();

// 睡眠 10 秒
Thread.sleep(10000);

connection.stop();
public class jmsMessageListener implements MessageListener {
public void onMessage(Message message) {
// 处理消息
}
}