How to start Camel route with autoStartup = false

I want to control when my route starts using RoutePolicy. So I defined it with autoStartup = false

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

To start the route, I tried:

public class MyRoutePolicy implements RoutePolicy {

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

    // More stuff omitted
}

Unfortunately, nothing happens. Javadoc for CamelContext.startRoute(String)may explain why:

Starts this route if it was previously stopped

How to start a route that has not been previously stopped?

I am using Camel 2.8.0 and updating is not an option.

I can start the route using the JMX console, but I do not want to depend on JMX.

+3
source share
2 answers

I was debugging Camel. It CamelContext.startRoute(String)does not seem to start the route with autoStartup = false.

The correct way to start a route:

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
}
+3

Java DSL : from("myEndpoint").autoStartup(isMyConfigEnabled())..., isMyConfigEnabled() - , .

+1

All Articles