嗨,我正在尝试为 MQ 队列设置一个监听器,它需要连续监听队列并通过 onMessage 函数传递任何新消息。程序不应退出。 以下是我的程序的片段。 在 MQQueueConnection.start 上,我在 onMessage 函数中遇到了问题,但在使用来自 MQ 的 1 条消息后,程序停止了。我希望程序永远运行并通过 onMessage 函数在队列中传递新消息。有什么想法我做错了吗? 使用 spring jms 类,它可以按要求工作,尽管我不想在这里使用 spring 。
public class MyListener implements MessageListener {
@Override
public void onMessage(Message message)
{
try
{
handleMessage(message,session);
}
catch (Exception exx)
{
onHandleMessageException(message, exx);
}
}
}
public class TestListener
{
public static void main(String[] args) {
MyListener myListener = new MyListener();
MQQueueConnectionFactory connFactory = new MQQueueConnectionFactory();
//MyApplicationContext - custom class for loading MQ params
MyApplicationContext obj=MyApplicationContext.getInstance();
connFactory.setHostName(obj.getHost());
connFactory.setPort(obj.getPort());
connFactory.setQueueManager(obj.getQueueManagerName());
connFactory.setChannel(obj.getChannel());
connFactory.setTransportType(obj.getTransportType());
MQQueueConnection connection=(MQQueueConnection) connFactory.createQueueConnection(obj.getMqUser(), obj.getMqPWD()) ;
MQQueueSession session=(MQQueueSession) connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
MQQueue queue = (MQQueue) session.createQueue("TEST.QUEUE");
MQQueueReceiver qReceiver = (MQQueueReceiver) session.createReceiver(queue);
qReceiver.setMessageListener(myListener);
// expect to start a new thread, which will constantly listen for new messages
//on the queue and deliver it in onMessage function.
//instead after receiving one message in onMessage, program exits
connection.start();
}
}
最佳答案
connection.start() 启动一个新线程,但该线程可能是 daemon线程,所以当程序结束时它也结束。您很幸运能收到 1 条消息。
例如,尝试在主程序末尾使用 Thread.sleep(60000),然后监听器将在空中停留一分钟,您可能会收到更多消息。
关于java - MQQueueConnection.start不会持续监听新消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26647928/