集成流组合
在 Spring Integration 中,MessageChannel
抽象作为一等公民,集成流的组合一直被认为是理所当然的。流中任何端点的输入通道都可以用于从任何其他端点发送消息,而不仅仅是从将此通道作为输出的端点的发送消息。此外,通过 @MessagingGateway
契约、内容丰富器组件、<chain>
等复合端点,以及现在的 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
定义自动装配即可。