Is there some solution to create a camel route dynamically, in time execution? In a common way, we explicitly define a camel route as:
from("direct:a")
.to("direct:b");
However, I want to create some routes in time execution when be required. For example, from a property file, the application will read the properties and create the routes using the properties. I'll have the code:
from({property1})
.to({property2});
If exists one more property file the application must create dynamically another route and add it in the camel context. Is that possible, someone can help me?
To create camel route(s) dynamically at runtime, you need to
Consume config files 1 by 1
This can be as simple as setting a file endpoint to consume files, e.g.
<from uri="file:path/to/config/files?noop=true"/>
<bean ref="pleaseDefineThisSpringBean" method="buildRoute" />
...
Create route by config file
Add a new route to CamelContext with the help of a routeBuilder
public void buildRoute(Exchange exchange) {
// 1. read config file and insert into variables for RouteBuilder
// 2. create route
SpringCamelContext ctx = (SpringCamelContext)exchange.getContext();
ctx.addRoutes(createRoutebyRouteBuilder(routeId, from_uri, to_uri));
}
protected static RouteBuilder createRoutebyRouteBuilder(final String routeId, final String from_uri, String to_uri) throws Exception{
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from (from_uri)
.routeId(routeId)
.to(to_uri);
}
};
}
Note: The function "addRoutes" will override existing route of same routeId
Yes of course you can do it. I am not sure what exactly do you meant by "in time execution".
1. If you are referring to something like you want to create routes by not hardcoding it in java code, but want to take it from properties file, then it is quite straightforward. You can just autowire the propertis in your class where you are creating routes and use them as any other variable.
for example
@Configuration
public class CamelConfig {
@Value("${from.route}")
String fromRoute;
@Value("${to.route}")
String toRoute;
@Bean
public RoutesBuilder routes() {
return new SpringRouteBuilder() {
@Override
public void configure() throws Exception {
from(fromRoute).to(toRoute);
}
};
}
}
2. If you want to add routes dynamically once the application context has already initialized, then you can do it like this
@Component
public class SomeBean {
@Value("${from.route}")
String fromRoute;
@Value("${to.route}")
String toRoute;
@Autowired
ApplicationContext applicationContext;
public void someMethod() {
CamelContext camelContext = (CamelContext) context.getBean(CamelContext.class);
new SpringRouteBuilder() {
@Override
public void configure() throws Exception {
from(fromRoute).to(toRoute);
}
};
}
}
Camel uses double braces to read from property value (http://camel.apache.org/properties.html), so:
from("{{property1}}")
.to("{{property2}}");