图例
说明
相当于一个循环,每次返回一个需要执行的一个或多个路由,知道返回null时不执行
java事例
from("direct:start")
// use a bean as the dynamic router
.dynamicRouter(method(DynamicRouterTest.class, "slip"));
public class DynamicRouterTest {
public static int invoked = 0;
/**
* 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(@Body String body) {
invoked++;
System.out.println("第" + invoked + "次执行");
System.out.println("body : " + body);
if (invoked == 1) {
return "direct:A";
} else if (invoked == 2) {
return "direct:B";
} else if (invoked == 3) {
return "direct:C";
} else if (invoked == 4) {
//可以执行多个,用逗号隔开
return "direct:A,direct:B";
}
// no more so return null
return null;
}
}
SpringXML事例
<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:A"/>
<transform><constant>Bye World</constant></transform>
</route>
</camelContext>
@DynamicRouter 注解
从camel2.4版本开始,你可以使用注解的方式来进行动态路由执行
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.
}
}