8.18. 动态路由器

动态路由器

动态路由器 模式(如 图 8.12 “动态路由器模式” 所示)可让您连续通过一系列处理步骤(在设计时不了解步骤序列)来连续路由消息。在运行时动态计算消息应通过的端点列表。每次消息从端点返回时,对 bean 的动态路由器调用重新发现路由中的下一端点。

图 8.12. 动态路由器模式

dynamic router

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

beware

您必须确保用于 dynamicRouter (如 bean)的表达式返回 null 来指明结尾。否则,动态Router 将继续处于无限循环中。

Camel 2.5 中的动态路由器主题

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

Java DSL

在 Java DSL 中,您可以使用 dynamicRouter,如下所示:

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

这将利用 bean 集成计算 slip on-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 命令支持以下选项:

Name

默认值

描述

uriDelimiter

,

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

ignoreInvalidEndpoints

false

如果端点 uri 无法解析,它应该被忽略。否则 Camel 将抛出异常,说明端点 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” 一样,您可以返回多个端点,其中每个端点由分隔符分隔。