2

I am using Camel with Spring Boot. The camel context is started on application started and it keeps running. On application shut down how to shut down the camel context.

Thanks in advance.

2 Answers2

4

I have written a custom solution by implementing spring's SmartLifeCycle which waits for other spring beans to stop before shutting down CamelContext. Use this class as it is, it would work fine.

@Component
public class SpringBootCamelShutDown implements SmartLifecycle {

    private static final Logger log = LoggerFactory.getLogger(SpringBootCamelShutDown.class);

    @Autowired
    private ApplicationContext appContext;

    @Override
    public void start() {}

    @Override
    public void stop() {}

    @Override
    public boolean isRunning() {
        SpringCamelContext context = (SpringCamelContext)appContext.getBean(CamelContext.class);
        return context.isStarted();
    }

    @Override
    public boolean isAutoStartup() {
        return true;
    }

    @Override
    public void stop(Runnable runnable) {
        SpringCamelContext context = (SpringCamelContext)appContext.getBean(CamelContext.class);
        if (!isRunning()) {
            log.info("Camel context already stopped");
            return;
        }

        log.info("Stopping camel context. Will wait until it is actually stopped");

        try {
            context.stop();
        } catch (Exception e) {
            log.error("Error shutting down camel context",e) ;
            return;
        }

        while(isRunning()) {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                log.error("Error shutting down camel context",e) ;
            }
        };

        // Calling this method is necessary to make sure spring has been notified on successful
        // completion of stop method by reducing the latch countdown value.
        runnable.run();
    }

    @Override
    public int getPhase() {
        return Integer.MAX_VALUE;
    }
}
rishi
  • 1,792
  • 5
  • 31
  • 63
  • I would mark this answer as answered if I were the one asked this question. Btw, don't we need 'runnable.run();' when camelContext had already stopped? – Venkatesh Laguduva Mar 29 '21 at 16:02
1

You can use CamelContext class stop method.

@Autowired CamelContext camelContext;

stop() - to shutdown (will stop all routes/components/endpoints etc and clear internal state/cache)

Refer http://camel.apache.org/spring-boot.html and http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/CamelContext.html

Alien
  • 15,141
  • 6
  • 37
  • 57