简体   繁体   中英

JMS closing client resources (MessageConsumer, Session, Connection)

I have a simple JMS client and I would like to close all the JMS related resources at the end, ie instances of MessageConsumer, Session, Connection. Each of these classes has a close() method that throws a JMSException. I read I have to close all of them and closing an instance of a Connection is not enough. So this is what I have so far:

        try {
            consumer.close();
            session.close();
            connection.close();
        } catch (JMSException e) {
            log.error(e.getMessage(), e);
        }

but if for example a consumer.close() throws an exception the session and the connection won't be closed. So a more correct approach would be:

    try {
        consumer.close();
    } catch (JMSException e) {
        log.error(e.getMessage(), e);
    }
    try {
        session.close();
    } catch (JMSException e) {
        log.error(e.getMessage(), e);
    }
    try {
        connection.close();
    } catch (JMSException e) {
        log.error(e.getMessage(), e);
    }

but it does not seem nice because of the code duplication. I find it hard to abstract it out more because none of these classes implement a common interface with a close() method (like Closable for example).

Do you know any better approach to close correctly all these 3 resources?

当您关闭父级时,子级也将关闭,因此您可以关闭会话以关闭它的生产者和消费者,或者您可以关闭连接以关闭它创建的所有内容。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM