在Java中运行时添加camel路由

时间:2012-05-04 15:06:23

标签: spring apache-camel

如何在Java中在运行时添加camel路由?我找到了一个Grails示例,但我已经用Java实现了它。

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

2 个答案:

答案 0 :(得分:15)

你可以简单地在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);
    }
}

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

https://svn.apache.org/repos/asf/camel/trunk/camel-core/src/test/java/org/apache/camel/builder/AddRoutesAtRuntimeTest.java

答案 1 :(得分:1)

@Himanshu, 请查看动态路由选项(换句话说路由单),它可以帮助您根据特定条件动态路由到不同的“目的地”。

检查驼峰网站中的动态路由器帮助链接;

http://camel.apache.org/dynamic-router.html

from("direct:start")
    // use a bean as the dynamic router
    .dynamicRouter(method(DynamicRouterTest.class, "slip"));

在滑动方法中;

/**
 * Use this method to compute dynamic where we should route next.
 *
 * @param body the message body
 * @return endpoints to go, or <tt>null</tt> to indicate the end
 */
public String slip(String body) {
    bodies.add(body);
    invoked++;

    if (invoked == 1) {
        return "mock:a";
    } else if (invoked == 2) {
        return "mock:b,mock:c";
    } else if (invoked == 3) {
        return "direct:foo";
    } else if (invoked == 4) {
        return "mock:result";
    }

    // no more so return null
    return null;
}

希望它有所帮助...

感谢。