如何从 JMS 队列中删除消息

2022-09-04 08:20:30

是否有任何 API 可以在不使用监视管理工具的情况下从 JMS 队列中删除消息。


答案 1

没有用于删除消息的直接 API。您可以调用 queueReceiver.receive() 方法从队列中删除消息。QueueBrowser 不会从队列中删除邮件。


答案 2

我不得不另外呼吁消费者删除消息。session.commit()

此外,API不起作用;改为调用。receivenowaitreceive(1000)

以下是我编写的一段代码:jboss

try {
  connection = connectionFactory.createConnection();
  session = connection.createSession(true,-1);
  Queue queue = (Queue) QueueConnectionFactory.getInitialContext().lookup("/queue/DLQ");
  QueueBrowser browser = session.createBrowser(queue);
  Enumeration<?> enum1 = browser.getEnumeration();

  while(enum1.hasMoreElements()) {
    TextMessage msg = (TextMessage)enum1.nextElement();
    MessageConsumer consumer = session.createConsumer(queue, "JMSMessageID='" +  msg.getJMSMessageID()  + "'");
    //You can try starting the connection outside while loop as well, I think I started it inside while loop by mistake, but since this code worked I am hence letting you know what worked  
    connection.start();
    Message message = consumer.receive(1000) ;
    if ( message != null ) {
        //do something with message
    }
  }
} 
finally {
  session.commit();
  consumer.close();
  browser.close();
  session.close();
  connection.close();
}

推荐