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

25 views
Skip to first unread message

Rajesh Thatikonda

unread,
Oct 10, 2023, 4:09:01 AM10/10/23
to rabbitmq-users
Wanted to close the channel and connection on the stop of web application where rabbitmq consumer is up and running

@Service
public class RabbitMQConsumer{

private static final Logger logger = LoggerFactory.getLogger(RabbitMQConsumer.class);

@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 but still not able to close the connection as these methods are not getting invoking on application stop
Reply all
Reply to author
Forward
0 new messages