訊息路由器
Spring Integration 原生提供了專門的路由器型別,包括
-
HeaderValueRouter
-
PayloadTypeRouter
-
ExceptionTypeRouter
-
RecipientListRouter
-
XPathRouter
與許多其他 DSL IntegrationFlowBuilder
EIP 方法一樣,route()
方法可以應用任何 AbstractMessageRouter
實現,或者為了方便起見,將 String
作為 SpEL 表示式或 ref
-method
對。此外,您可以配置 route()
與 lambda,並使用 lambda 作為 Consumer<RouterSpec<MethodInvokingRouter>>
。流暢的 API 還提供了 AbstractMappingMessageRouter
選項,例如 channelMapping(String key, String channelName)
對,如下例所示
@Bean
public IntegrationFlow routeFlowByLambda() {
return IntegrationFlow.from("routerInput")
.<Integer, Boolean>route(p -> p % 2 == 0,
m -> m.suffix("Channel")
.channelMapping(true, "even")
.channelMapping(false, "odd")
)
.get();
}
以下示例展示了一個簡單的基於表示式的路由器
@Bean
public IntegrationFlow routeFlowByExpression() {
return IntegrationFlow.from("routerInput")
.route("headers['destChannel']")
.get();
}
routeToRecipients()
方法接受一個 Consumer<RecipientListRouterSpec>
,如下例所示
@Bean
public IntegrationFlow recipientListFlow() {
return IntegrationFlow.from("recipientListInput")
.<String, String>transform(p -> p.replaceFirst("Payload", ""))
.routeToRecipients(r -> r
.recipient("thing1-channel", "'thing1' == payload")
.recipientMessageSelector("thing2-channel", m ->
m.getHeaders().containsKey("recipient")
&& (boolean) m.getHeaders().get("recipient"))
.recipientFlow("'thing1' == payload or 'thing2' == payload or 'thing3' == payload",
f -> f.<String, String>transform(String::toUpperCase)
.channel(c -> c.queue("recipientListSubFlow1Result")))
.recipientFlow((String p) -> p.startsWith("thing3"),
f -> f.transform("Hello "::concat)
.channel(c -> c.queue("recipientListSubFlow2Result")))
.recipientFlow(new FunctionExpression<Message<?>>(m ->
"thing3".equals(m.getPayload())),
f -> f.channel(c -> c.queue("recipientListSubFlow3Result")))
.defaultOutputToParentFlow())
.get();
}
.routeToRecipients()
定義中的 .defaultOutputToParentFlow()
方法允許您將路由器的 defaultOutput
設定為一個閘道器,以便在主流程中繼續處理不匹配的訊息。
另請參閱 Lambdas 和 Message<?>
引數。