How do i stop @JmsListener from listening a queue using JmsListenerEndpointRegistry in spring boot?

44 Views Asked by At
@Component
public class MyJmsListener{
    @Autowired
    private MyService myService;

    @JmsListener(destination="${queue.nameOne}")
    void receiveMessageOne(Message message){
        myService.process(message);
    }
    @JmsListener(destination="${queue.nameTwo}")
    void receiveMessageTwo(Message message){
        myService.process(message);
    }

    @JmsListener(destination="${queue.nameThree}")
    void receiveMessageThree(Message message){
        myService.process(message);
    }


}

**I have tried with @Conditional(demoClass implements Condition) annotation which will make the bean based on my demoClass and the bean was created . The problem is MyJmsListener class has three @JmsListener, if i would not make bean of MyJmsListener class , so all my @JmsListener will deacivate . **My query is to stop and start @JmsListener based on some codition in Spring Boot.

1

There are 1 best solutions below

4
Popescu M On

My understanding is that you want MyJmsListener to stop/start listening on the queues based on a property. For this you can use ConditionalOnProperty like below:

@ConditionalOnProperty(prefix = "jms", name = "enabled", havingValue = "true")

You have to declare jms.enabled=true and you will get the on off switch you require.

In case you need to switch between queues and listen to just one at a time then you need to split them in 3 different beans and have them starting based on a property similar to above.

To do this programatically then you can use JmsListenerEndpointRegistry

@RestController
@RequestMapping("/jms")
public class JmsListenerController {

@Autowired
ApplicationContext ctx;

@RequestMapping(value="/stop", method= RequestMethod.GET)
public @ResponseBody
String stopJmsListener() {
    JmsListenerEndpointRegistry jmsRegistry=
            ctx.getBean("jmsRegistry", JmsListenerEndpointRegistry.class);
    jmsRegistry.stop();
    return "Jms Listeners Stopped";
}

You can create something similar to start the app.