其他分享
首页 > 其他分享> > spring-如何使用autoStartup = false启动骆驼路线

spring-如何使用autoStartup = false启动骆驼路线

作者:互联网

我想使用RoutePolicy控制何时启动我的路线.因此,我已经使用autoStartup = false定义了它

<camel:route id="myRoute" routePolicyRef="myRoutePolicy" autoStartup="false">
    <!-- details omitted -->
</camel:route>

要开始路线,我尝试:

public class MyRoutePolicy implements RoutePolicy {

    // Does NOT work!
    @Override
    public void onInit(Route route) {
        if(shouldStartRoute(route)) {
            camelContext.startRoute(route.getId());
        }
    }

    // More stuff omitted
}

不幸的是,什么也没有发生. CamelContext.startRoute(String)的Javadoc可以解释原因:

Starts the given route if it has been previously stopped

如何启动以前未停止的路线?

我正在使用骆驼2.8.0,并且不能升级.

我可以使用JMX控制台启动路由,但是我不想依赖JMX.

解决方法:

我一直在调试骆驼.似乎CamelContext.startRoute(String)不会使用autoStartup = false来启动路由.

开始路线的正确方法是:

ServiceHelper.startService(route.getConsumer());

但这在我的RoutePolicy中对我不起作用:

public class MyRoutePolicy implements RoutePolicy {

    // Does NOT work either!
    @Override
    public void onInit(Route route) {
        if(shouldStartRoute(route)) {
            ServiceHelper.startService(route.getConsumer());
        }
    }

    // More stuff omitted
}

这里的问题是route.getConsumer()返回null.您必须等到Camel上下文初始化后才能调用ServiceHelper.startService(consumer).所以这是起作用的:

public class MyRoutePolicy extends EventNotifierSupport implements RoutePolicy {
    private final Collection<Route> routes = new HashSet<>();

    @Override
    public void onInit(Route route) {
        routes.add(route);
        CamelContext camelContext = route.getRouteContext().getCamelContext();
        ManagementStrategy managementStrategy = camelContext.getManagementStrategy();
        if (!managementStrategy.getEventNotifiers().contains(this)) {
            managementStrategy.addEventNotifier(this);
        }
    }

    // Works!
    @Override
    public void notify(EventObject event) throws Exception {
        if(event instanceof CamelContextStartedEvent) {
            for(Route route : routes) {
                if(shouldStartRoute(route)) {
                    ServiceHelper.startService(route.getConsumer());
                }
            }
        }
    }

    // More stuff omitted
}

标签:apache-camel,spring
来源: https://codeday.me/bug/20191029/1963470.html