集成流组合
由于 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 定义中即可。