一尘不染

在Java中运行时添加camel路由

spring

如何在Java运行时添加camel路线?我找到了Grails示例,但是已经用Java实现了。

我的applicationContext.xml已经有一些预定义的静态路由,我想在运行时为其添加一些动态路由。可能吗?因为包括动态路由的唯一方法是编写route.xml,然后将路由定义加载到上下文。它如何在现有静态路由上工作?


阅读 1277

收藏
2020-04-18

共2个答案

一尘不染

你可以在CamelContext上简单地调用一些不同的API来添加路由…类似这样的东西

context.addRoutes(new MyDynamcRouteBuilder(context, "direct:foo", "mock:foo"));
....
private static final class MyDynamcRouteBuilder extends RouteBuilder {
    private final String from;
    private final String to;

    private MyDynamcRouteBuilder(CamelContext context, String from, String to) {
        super(context);
        this.from = from;
        this.to = to;
    }

    @Override
    public void configure() throws Exception {
        from(from).to(to);
    }
}
2020-04-18
一尘不染

请参阅此单元测试以获取完整示例…

/ ** *根据一个或多个许可给Apache软件基金会(ASF) *贡献者许可协议。请参阅随发布的NOTICE文件 *此项工作提供有关版权所有权的更多信息。 * ASF在Apache许可证2.0版下将此文件许可给您 *(“许可证”);除非遵守以下规定,否则您不得使用此文件 *许可证。您可以在以下位置获得许可的副本: * * http://www.apache.org/licenses/LICENSE-2.0 * *除非适用法律要求或书面同意,否则软件 *根据许可协议分发的内容是按“原样”分发的, *不作任何明示或暗示的保证或条件。 *有关特定语言的管理权限,请参阅许可证 *许可中的限制。 * /

包org.apache.camel.builder;

导入org.apache.camel.CamelContext;
导入org.apache.camel.ContextTestSupport;

/ ** *测试如何使用RouteBuilder在运行时添加路由 * * @版本 * /

public class AddRoutesAtRuntimeTest extends ContextTestSupport {

    public void testAddRoutesAtRuntime() throws Exception {
        getMockEndpoint("mock:start").expectedMessageCount(1);
        template.sendBody("direct:start", "Hello World");
        assertMockEndpointsSatisfied();
        assertEquals(1, context.getRoutes().size());

        getMockEndpoint("mock:foo").expectedMessageCount(1);
        context.addRoutes(new MyDynamcRouteBuilder(context, "direct:foo", "mock:foo"));
        template.sendBody("direct:foo", "Bye Camel");
        assertMockEndpointsSatisfied();
        assertEquals(2, context.getRoutes().size());

        getMockEndpoint("mock:bar").expectedMessageCount(1);
        context.addRoutes(new MyDynamcRouteBuilder(context, "direct:bar", "mock:bar"));
        template.sendBody("direct:bar", "Hi Camel");
        assertMockEndpointsSatisfied();
        assertEquals(3, context.getRoutes().size());
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                // here is an existing route
                from("direct:start").to("mock:start");
            }
        };
    }

/** * This route builder is a skeleton to add new routes at runtime */

private static final class MyDynamcRouteBuilder extends RouteBuilder {
     private final String from;
     private final String to;

     private MyDynamcRouteBuilder(CamelContext context, String from, String to) {
         super(context);
         this.from = from;
         this.to = to;
     }

     @Override
     public void configure() throws Exception {
         from(from).to(to);
     }
 }
}
2020-04-18