【问题标题】:MQQueueConnection.start does not continuously listen for new messagesMQQueueConnection.start 不会持续监听新消息
【发布时间】:2014-10-30 18:19:47
【问题描述】:

您好,我正在尝试为 MQ 队列设置一个侦听器,该侦听器需要连续侦听队列并通过 onMessage 函数传递任何新消息。程序不应退出。 以下是我的程序的 sn-p。 在 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(); 
   }
}

【问题讨论】:

  • 缺少 util.Timer, executor, .... 合理的周期,创建可管理但无限循环,main 中的每个代码行都应该在构造函数中
  • 你是说,使用定时器重复执行main函数中的整个代码?有没有更好的方法来实现所需的目标?
  • 如果你的主线程除了启动消息监听器之外没有做任何事情,那么主线程本身可以调用 Queue.Receive() 方法来接收消息。
  • 在启动消息侦听器后,还有一个代码可以将数据发送到 MQ。我只想通过 onMessage 处理程序来处理它

标签: java jms mq


【解决方案1】:

connection.start() 启动一个新线程,但该线程可能是daemon 线程,所以它在程序结束时结束。您很幸运收到了 1 条消息。

例如,在 main 的末尾尝试一个 Thread.sleep(60000),然后监听器将在空中停留一分钟,您可能会收到更多消息。

【讨论】:

  • 好吧,你是说,我必须自己通过睡眠或线程等待来保持我的主线程在空中。 connection.start 不会让主线程保持在空中
  • 谢谢我要阻塞主线程,使用while(true) { synchronized(threadWaitObj) { threadWaitObj.wait(); } }并在onMessage中调用synchronized(threadWaitObj) { threadWaitObj.notify(); }
猜你喜欢
  • 2023-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-16
  • 2018-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多