2

我看到很多例子,比如 http://hursleyonwmq.wordpress.com/2007/05/29/simplest-sample-applications-using-websphere-mq-jms/,甚至在 IBM publib 上。我猜这段代码有一个缺陷:队列连接在主块中关闭,而不是在最后,如我预期的那样。

什么是关闭 MQ 连接而不泄漏的正确方法?

4

2 回答 2

1

我认为最好在最后完成。IE

finally
{
   try
   {
      session.close();
   }
   catch (Exception ex)
   {
      System.err.println("session.close() : " + ex.getLocalizedMessage());
   }

   try
   {
      connection.close();
   }
   catch (Exception ex)
   {
      System.err.println("connection.close() : " + ex.getLocalizedMessage());
   }
}
于 2014-07-10T17:42:45.327 回答
0

IBM MQ 自 8.0.0(自 2014 年以来)版本支持 JMS 2.0。所以所有 QueueConnection、QueueSession QueueSender 和 QueueReceiver 都实现了 java.lang.AutoCloseable参见 ibm mq 规范

try (QueueConnection connection = connectionFactory.createQueueConnection();
     //create a session that is not transacted and has an acknowledgment mode 
     QueueSession session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE)) 
    {
        Queue queue = session.createQueue("queue:///Q1");

        try (QueueSender sender = session.createSender(queue);
             QueueReceiver receiver = session.createReceiver(queue);) 
        {
            //getting and sending messages...
        }

    } catch (JMSException e) {
        //handling jms exceptions...
    }

或使用 JMS 2.0 JMSContext

try (JMSContext context = connectionFactory.createContext();) 
    {
        context.createProducer().send(context.createQueue("queue:///Q1"), "text");
    } catch (JMSRuntimeException ex) {
        // handle exception (details omitted)
    }
于 2019-12-28T09:57:46.340 回答