Message Routers

Spring Integration 本机提供专门的路由器类型,包括:

  • HeaderValueRouter

  • PayloadTypeRouter

  • ExceptionTypeRouter

  • RecipientListRouter

  • XPathRouter

与许多其他 DSL IntegrationFlowBuilder EIP 类似,route() 方法可以应用任何 AbstractMessageRouter 实现或简单起见,可以将 String 用作 SpEL 表达式或 ref-method 对。此外,你可以使用 lambda 配置 route() 并为 Consumer<RouterSpec<MethodInvokingRouter>> 使用 lambda。流畅的 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 设置为网关,以继续处理主流程中不匹配的消息。

另见 xref:dsl/java-basics.adoc#java-dsl-class-cast[Lambdas And Message<?> 参数。