How do I start a Camel route with autoStartup=false
apache-camel, spring
Solution
I've been debugging Camel. It seems that `CamelContext.startRoute(String)` does not start a route with autoStartup=false.
The right way to start a route is:
ServiceHelper.startService(route.getConsumer());
But it didn't work for me in my `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
}
The problem here is that `route.getConsumer()` returns `null`. You have to wait until the Camel context is initialized to call `ServiceHelper.startService(consumer)`. So here is what does work:
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
}
Problem
I want to control when my route starts up using a `RoutePolicy`. Therefore, I have 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. The Javadoc for `CamelContext.startRoute(String)` may explain why: Starts the given route if it has been previously stopped How do I start a route that hasn't previously been stopped? I'm using Camel 2.8.0 and upgrading is not an option. I can start the route using a JMX console, but I don't want to depend on JMX.