Search code examples
apache-camelibm-mq

How can I check if a queue is empty and then stop the apache camel route that os listening to the queue


I have an apache camel route that will be started by a process. Once the route is started it will process all of the messages on the queue. I want to stop the route once the queue is emptied out, so is it possible to do it in camel and maybe provide a short example.


Solution

  • This is the approach that worked for me:

    Route configuration:

    from("direct:start")
        .routeId("testRoute")
        .setHeader("shutDownRoute").method(myBean)
        // you business logic 
        .choice()
            when(header("shutDownRoute").isEqualTo(true))
                .toD("controlbus:route?async=true&routeId=${routeId}&action=stop")
            end();
    

    MyBean.java

    @Service
    public class MyBean {
      private JmsTemplate jmsTemplate;
      private String queueName;
    
      @Autowired
      public MyBean (JmsTemplate jmsTemplate, String queueName) {
        this.jmsTemplate = jmsTemplate;
        this.queueName = queueName;
      }
    
      private Message browseMessageFromQueue(String queueName) {
        BrowserCallback<Message> browserCallback = 
              (session, browser) -> {
            Enumeration<?> enumeration = browser.getEnumeration();
            if(enumeration.hasMoreElements()) {
                return (Message) enumeration.nextElement();
            }
            return null;
        };
        return jmsTemplate.browse(queueName, browserCallback);
      }
    
      @Handler
      public boolean isLastMessage() {
        Message message = browseMessageFromQueue(queueName);
        return message == null; 
      }
    }