如何在Camel中动态添加和启动路由?

时间:2015-12-16 12:05:23

标签: java templates routes apache-camel boilerplate

我试图从Camel中的路线中删除一些样板。

例如,让我们考虑两条相似的路线,并且可以生成大部分内部路径。我创建了一个组件"模板",它创建了TemplateEndpoint,并修改了XML配置以使用模板组件。

TemplateEndpoint.generateRoute(在StartupListener中定义)调用自定义方法TemplateEndpoint.setSuffix(添加路由定义)。 因此,当Camel上下文启动时,路由定义出现在上下文中,但框架不会为它们创建路由服务,因此它们不会开始。

如何启动StartupListener中添加的路线?

我可能面临一个XY问题,你可以建议我一个更好的方法来做这个技巧(即动态添加和启动路线)

类似的两条路线

<route id="route_A">
  <from uri="restlet:/another1?restletMethods=GET" />
  <to uri="first:run_A" />
  <to uri="second:jump_A" />     
  <to uri="third:fly_A" />
</route>

<route id="route_B">
  <from uri="restlet:/another2?restletMethods=GET" />
  <to uri="first:run_B" />
  <to uri="second:jump_B" />     
  <to uri="third:fly_B" />
</route>

修改后的XML

<route id="route_A">
  <from uri="restlet:/another1?restletMethods=GET" />
  <to uri="template://?suffix=A" />
</route>

<route id="route_B">
  <from uri="restlet:/another2?restletMethods=GET" />
  <to uri="template://?suffix=B" />
</route>

端点

public class TemplateEndpoint extends DefaultEndpoint {

  /* some methods omitted */ 
  // this endpoint creates a DefaultProducer, which does nothing

  public void setSuffix(final String suffix) throws Exception {

    this.getCamelContext().addStartupListener(new StartupListener() {
      @Override
      public void onCamelContextStarted(CamelContext context, boolean alreadyStarted) throws Exception {       
        generateRoute(suffix)
        .addRoutesToCamelContext(context);
      }
    });
  }

  private RouteBuilder generateRoute(final String suffix){ 
     final Endpoint endpoint = this;

     return new RouteBuilder() {
        @Override
        public void configure() throws Exception {
          from(endpoint)
           .to("first:run_" + suffix)
           .to("second:jump_" + suffix)
           .to("third:fly_" + suffix);
       }
  }
}

1 个答案:

答案 0 :(得分:5)

我会创建一个动态路由构建器,例如

var largeHtml= "<s:property value=\'ss\' />";

并将其添加到某些事件上,例如

public class MyRouteBuilder extends RouteBuilder {

            private String another;
            private String letter;

            public MyRouteBuilder(CamelContext context,String another, String letter) {
                super(context);
                this.another=another;
                this.letter=letter;
            }

            @Override
            public void configure() throws Exception {
                super.configure();
                from("restlet:/"+another+"?restletMethods=GET")
                .to("first:run_"+letter)
                .to("second:jump_"+letter)
                .to("third:fly_"+letter);
            }
    }
相关问题