user3504337
user3504337

Reputation: 41

How to stop camel context gracefully in Springboot application

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.

Upvotes: 2

Views: 2315

Answers (2)

rishi
rishi

Reputation: 1842

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;
    }
}

Upvotes: 4

Alien
Alien

Reputation: 15878

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

Upvotes: 1

Related Questions