Dynamic routing Apache Camel

会有一股神秘感。 提交于 2019-12-02 08:27:40

To create camel route(s) dynamically at runtime, you need to

  1. 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" />
    ...
  1. 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}}");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!