8.18. 动态路由器

动态路由器

图 8.12 “动态路由器模式” 所示,动态路由器 模式允许您通过一系列处理步骤连续路由消息,其中设计时不已知步骤序列。在运行时动态计算消息的端点列表。每次消息从端点返回时,在 bean 上返回动态路由器调用,以便在路由中发现下一个端点。

图 8.12. 动态路由器模式

动态路由器

Camel 2.5 中,我们在 DSL 中引入了一个动态 路由器,类似于评估 slip on-fly 的动态 第 8.7 节 “路由 Slip”

beware

您必须确保用于 dynamicRouter 的表达式(如 bean)返回 null 以表示结尾。否则,dynamicRouter 会继续进行无限循环。

Camel 2.5 中的动态路由器开始

从 Camel 2.5 中,第 8.18 节 “动态路由器” 更新交换属性 Exchange.SLIP_ENDPOINT,其当前的端点通过 slip 推进。这可让您了解交换是通过 slip 进行的。(它是滑动,因为 第 8.18 节 “动态路由器” 的实现基于 第 8.7 节 “路由 Slip”。)

Java DSL

在 Java DSL 中,您可以使用 动态Router,如下所示:

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

它们利用 bean 集成来计算滑动 ( fly )上的,该集成可以按以下方式实施:

// Java
/**
 * 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;
    }
注意

前面的示例 不是 线程安全。您必须将状态存储在 Exchange 上,以确保线程安全。

Spring XML

与 Spring XML 中的相同示例是:

<bean id="mySlip" class="org.apache.camel.processor.DynamicRouterTest"/>

<camelContext xmlns="http://camel.apache.org/schema/spring">
    <route>
        <from uri="direct:start"/>
        <dynamicRouter>
            <!-- use a method call on a bean as dynamic router -->
            <method ref="mySlip" method="slip"/>
        </dynamicRouter>
    </route>

    <route>
        <from uri="direct:foo"/>
        <transform><constant>Bye World</constant></transform>
        <to uri="mock:foo"/>
    </route>

</camelContext>

选项

dynamicRouter DSL 命令支持以下选项:

名称

默认值

描述

uriDelimiter

,

第 II 部分 “路由表达式和指定语言” 返回多个端点时使用的分隔符。

ignoreInvalidEndpoints

false

如果无法解析 endpoint uri,它应该被忽略。否则,Camel 会抛出一个异常,说明 endpoint uri 无效。

@DynamicRouter annotation

您还可以使用 @DynamicRouter 注释。例如:

// Java
public class MyDynamicRouter {

    @Consume(uri = "activemq:foo")
    @DynamicRouter
    public String route(@XPath("/customer/id") String customerId, @Header("Location") String location, Document body) {
        // query a database to find the best match of the endpoint based on the input parameteres
        // return the next endpoint uri, where to go. Return null to indicate the end.
    }
}

路由 方法会在消息通过 slip 时重复调用。其理念是返回下一个目的地的端点 URI。返回 null 以表示结尾。如果您像 第 8.7 节 “路由 Slip” 一样,您可以返回多个端点,其中每个端点通过分隔符分隔。