Home > Back-end >  Spring AMQP: Stopping a SimpleConsumer from DirectMessageListenerContainer
Spring AMQP: Stopping a SimpleConsumer from DirectMessageListenerContainer

Time:06-09

I have a use case where I am dynamically registering and removing a queue to and from a container based on some predicate. I am using a DirectMessageListenerContainer based on the advice given in the documentation as per my needs. Those dynamic queues are temporary ones that should get deleted if they have no messages and are not in use. Right now I have a Scheduler running periodically which deregisters the queue from the container if the predicate is true.

For me, the problem is even after removing the queue from the container the consumer bound to the queue is not getting released/stopped and thus the queue is not getting eligible for delete(due to the in-use policy by the consumer).

Is there a way to release or stop a consumer without restarting the container?

CodePudding user response:

When you remove a queue, its consumer(s) are canceled.

This works as expected:

@SpringBootApplication
public class So72540658Application {

    public static void main(String[] args) {
        SpringApplication.run(So72540658Application.class, args);
    }

    @Bean
    DirectMessageListenerContainer container(ConnectionFactory cf) {
        DirectMessageListenerContainer dmlc = new DirectMessageListenerContainer(cf);
        dmlc.setQueueNames("foo", "bar");
        dmlc.setMessageListener(msg -> {});
        return dmlc;
    }

    @Bean
    ApplicationRunner runner(DirectMessageListenerContainer container) {
        return args -> {
            System.out.println("Hit enter to remove bar");
            System.in.read();
            container.removeQueueNames("bar");
        };
    }
}

enter image description here

Hit enter; then:

enter image description here

Perhaps your consumer thread is stuck someplace? Try taking a thread dump. If you can't figure it out; post an MCRE somplace.

  • Related