3

我希望在消息驱动的 bean onmessage 方法中实现以下逻辑

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

如果我能得到一个实现这个逻辑的代码示例,我将不胜感激?

4

1 回答 1

0

您可能想要执行类似此代码的操作。但是,将侦听器保留给一个消费者,不要同时进行一次负载平衡,否则这将变得很棘手。如果您在 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();
}
于 2012-09-09T21:11:25.007 回答