集成流组合
有了 MessageChannel
抽象作为 Spring Integration 中的一等公民,集成流的组合性一直是可以预期的。流中任何端点的输入通道都可以用于从任何其他端点发送消息,而不仅仅是从将此通道作为输出的那个端点发送。此外,通过 @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
定义进行自动装配即可。