Not able to close the channel and connection for rabbitmq programmatically in java

Wanted to close the channel and connection on the stop of web application where rabbitmq consumer is up and running

@Autowired
private ConnectionFactory connectionFactory;

private Connection connection;

private Channel channel;

public String consumeMessage(String queueName, Boolean flag, DeliverCallback deliverCallback, CancelCallback cancelCallback) throws IOException, TimeoutException {
    connection = connectionFactory.createConnection();
    channel = connection.createChannel(true);
    return channel.basicConsume(queueName, flag, deliverCallback, cancelCallback);
}

public void cancelConsumer(String consumerTag) throws IOException, TimeoutException {
    if(channel != null && channel.isOpen()){
       channel.basicCancel(consumerTag);
    }
}

@Override
protected void finalize() throws Throwable {
    logger.info("inside finalize method");
    if(channel != null && channel.isOpen()){
        logger.info("channel.isOpen() "+channel.isOpen());
        channel.close();
        logger.info("after closing, checking channel.isOpen() "+channel.isOpen());
    }
    if(connection != null && connection.isOpen()){
        logger.info("connection.isOpen() "+connection.isOpen());
        connection.close();
        logger.info("after closing, checking connection.isOpen() "+connection.isOpen());
    }
}

Tried with finalize, destroy and postProcess

Read more here: Source link