如何从队列中手动读取N个消息,或者如果在onmessage()方法中已经过了Y时间?

时间:2012-09-09 18:14:03

标签: transactions jms mq

我希望在我的Message driven beans onmessage方法

中实现以下逻辑

读取N条消息或等待Y时间,以先发生者为准,然后提交交易。

如果我能获得实现此逻辑的代码示例,我将非常感激吗?

Ť

1 个答案:

答案 0 :(得分:0)

像这样的代码可能是你想要的。 将侦听器保留给单个消费者,但没有并发,负载平衡的once,或者这将变得棘手。如果你在JEE6上,你可能想通过注释注入jms资源。如果没有

,接收呼叫将阻止等待Y / N时间
public void onMessage(Message msg) {

  // So we got a message, let's grab the JMS resources
  // Note that these could be injected as well, for convenience

  InitialContext context = new InitialContext();
  ConnectionFactory factory = (ConnectionFactory) context.lookup("java:comp/env/jms/connectionFactory");
  Destination destination = (Destination) context.lookup("java:comp/env/jms/myQueue");
  Connection connection = factory.createConnection();
  connection.start();
  MessageConsumer consumer = session.createConsumer(destination);
  Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
  // TODO: handle msg here

  // So, let's start look for msgs.
  for (int i=0; i<N; i++) {
      Message msg_i = consumer.receive(Y/N);
      // Handle msg_i here.
  }
  consumer.close();
  session.close();
  connection.close();
}