如何在Springboot应用程序中优雅地停止骆驼上下文

时间:2018-08-28 10:14:15

标签: spring-boot apache-camel camel-ftp

我在Spring Boot中使用Camel。骆驼上下文在应用程序启动时启动,并保持运行。在应用程序关闭时,如何关闭骆驼上下文。

谢谢。

2 个答案:

答案 0 :(得分:1)

您可以使用CamelContext类的stop方法。

@Autowired CamelContext camelContext;

stop()-关机(将停止所有路由/组件/端点等,并清除内部状态/缓存)

引用http://camel.apache.org/spring-boot.htmlhttp://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/CamelContext.html

答案 1 :(得分:0)

我通过实现spring的SmartLifeCycle编写了一个自定义解决方案,该方法在关闭CamelContext之前等待其他spring bean停止。按原样使用此类,它将正常工作。

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