MQ правильный способ закрыть соединение
Я видел множество примеров, таких как http://hursleyonwmq.wordpress.com/2007/05/29/simplest-sample-applications-using-websphere-mq-jms/, даже в публикации IBM. Как я полагаю, в этом коде был недостаток: соединение с очередью закрыто в главном блоке, а не окончательно, как я ожидал.
Как правильно закрыть соединение MQ без утечек?
1 ответ
Решение
Я думаю, что лучше сделать это в конце концов. т.е.
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());
}
}
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)
}