集成流组合

由于 `MessageChannel` 抽象是 Spring Integration 中的一级公民,集成流的组合一直被认为是理所当然的。流中任何端点的输入通道都可以用来从任何其他端点发送消息,而不仅仅是那些将此通道作为输出的端点。此外,借助 `@MessagingGateway` 合约、内容增强器(Content Enricher)组件、像 `` 这样的复合端点,以及现在通过 `IntegrationFlow` bean(例如 `IntegrationFlowAdapter`),将业务逻辑分布到更短、可重用的部分中是足够直接的。最终组合所需的只是关于用于发送或接收的 `MessageChannel` 的知识。

从 `5.5.4` 版本开始,为了进一步抽象 `MessageChannel` 并向最终用户隐藏实现细节,`IntegrationFlow` 引入了 `from(IntegrationFlow)` 工厂方法,允许从现有流的输出开始当前 `IntegrationFlow`。

@Bean
IntegrationFlow templateSourceFlow() {
    return IntegrationFlow.fromSupplier(() -> "test data")
            .channel("sourceChannel")
            .get();
}

@Bean
IntegrationFlow compositionMainFlow(IntegrationFlow templateSourceFlow) {
    return IntegrationFlow.from(templateSourceFlow)
            .<String, String>transform(String::toUpperCase)
            .channel(c -> c.queue("compositionMainFlowResult"))
            .get();
}

另一方面,`IntegrationFlowDefinition` 添加了一个 `to(IntegrationFlow)` 终端操作符,以便在其他流的输入通道处继续当前流。

@Bean
IntegrationFlow mainFlow(IntegrationFlow otherFlow) {
    return f -> f
            .<String, String>transform(String::toUpperCase)
            .to(otherFlow);
}

@Bean
IntegrationFlow otherFlow() {
    return f -> f
            .<String, String>transform(p -> p + " from other flow")
            .channel(c -> c.queue("otherFlowResultChannel"));
}

在流的中间进行组合可以通过现有的 `gateway(IntegrationFlow)` EIP 方法简单实现。通过这种方式,我们可以将流从更简单、可重用的逻辑块组合起来,构建任意复杂度的流。例如,您可以将一个包含 `IntegrationFlow` bean 的库添加为依赖项,只需将其配置类导入到最终项目中并进行自动注入,即可用于您的 `IntegrationFlow` 定义。