Search code examples
springrabbitmqamqpspring-amqp

How do I hook into Channel closed event? Once per channel opened


I have an annotation-based Rabbit consumer represented by a @RabbitListener-annotated method.

I also have a configuration class to configure my Factory e.g.

@Bean
public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(
    ConnectionFactory connectionFactory) {
  var factory = new SimpleRabbitListenerContainerFactory();
  factory.setConnectionFactory(connectionFactory);
  ...
  return factory;
}

Sometimes my listener's code hits a PRECONDITION_FAILED error because it passes the broker's delivery acknowledgement timeout. I want to run some handling code whenever this happens.

I know that channel.addShutdownListener() exists but I don't know where to put it. I can't use the listener's method channel reference because that would add a listener for every message I process, which is not ideal.

I also understand that when a channel is closed, the listener will internally keep using the same ListenerContainer but with a new channel, so I will need to register the shutdown listener with the new channel in that case.

Basically, I need to add my handling code ONCE to each channel that is opened for my message listener.


Solution

  • See AbstractConnectionFactory.addChannelListener(ChannelListener) configuration.

    https://docs.spring.io/spring-amqp/docs/current/reference/html/#connection-channel-listeners