子流支援
某些 if…else 和 publish-subscribe 元件提供了透過子流指定其邏輯或對映的能力。最簡單的例子是 .publishSubscribeChannel(),如下例所示
@Bean
public IntegrationFlow subscribersFlow() {
return flow -> flow
.publishSubscribeChannel(Executors.newCachedThreadPool(), s -> s
.subscribe(f -> f
.<Integer>handle((p, h) -> p / 2)
.channel(c -> c.queue("subscriber1Results")))
.subscribe(f -> f
.<Integer>handle((p, h) -> p * 2)
.channel(c -> c.queue("subscriber2Results"))))
.<Integer>handle((p, h) -> p * 3)
.channel(c -> c.queue("subscriber3Results"));
}
你可以透過獨立的 IntegrationFlow @Bean 定義實現相同的結果,但我們希望你發現這種子流式的邏輯組合方式很有用。我們發現它能使程式碼更短(因此更具可讀性)。
從 5.3 版本開始,提供了基於 BroadcastCapableChannel 的 publishSubscribeChannel() 實現,用於在代理支援的訊息通道上配置子流訂閱者。例如,我們現在可以在 Jms.publishSubscribeChannel() 上將多個訂閱者配置為子流
@Bean
public JmsPublishSubscribeMessageChannelSpec jmsPublishSubscribeChannel() {
return Jms.publishSubscribeChannel(jmsConnectionFactory())
.destination("pubsub");
}
@Bean
public IntegrationFlow pubSubFlow(BroadcastCapableChannel jmsPublishSubscribeChannel) {
return f -> f
.publishSubscribeChannel(jmsPublishSubscribeChannel,
pubsub -> pubsub
.subscribe(subFlow -> subFlow
.channel(c -> c.queue("jmsPubSubBridgeChannel1")))
.subscribe(subFlow -> subFlow
.channel(c -> c.queue("jmsPubSubBridgeChannel2"))));
}
類似的 publish-subscribe 子流組合提供了 .routeToRecipients() 方法。
另一個例子是在 .filter() 方法上使用 .discardFlow() 代替 .discardChannel()。
.route() 值得特別關注。考慮以下示例
@Bean
public IntegrationFlow routeFlow() {
return f -> f
.<Integer, Boolean>route(p -> p % 2 == 0,
m -> m.channelMapping("true", "evenChannel")
.subFlowMapping("false", sf ->
sf.<Integer>handle((p, h) -> p * 3)))
.transform(Object::toString)
.channel(c -> c.queue("oddChannel"));
}
.channelMapping() 繼續像常規 Router 對映一樣工作,但 .subFlowMapping() 將該子流繫結到主流程。換句話說,任何路由器的子流在 .route() 之後都會返回到主流程。
|
有時,你需要從
Caused by: org.springframework.beans.factory.BeanCreationException:
The 'currentComponent' (org.springframework.integration.router.MethodInvokingRouter@7965a51c)
is a one-way 'MessageHandler' and it isn't appropriate to configure 'outputChannel'.
This is the end of the integration flow.
當你將子流配置為 lambda 時,框架會處理與子流的請求-回覆互動,不需要閘道器。 |
子流可以巢狀到任何深度,但我們不建議這樣做。事實上,即使在路由器的情況下,在流程中新增複雜的子流很快就會變得像一盤義大利麵條,讓人難以理解。
|
在 DSL 支援子流配置的情況下,當通常需要通道用於正在配置的元件時,並且該子流以
框架在內部建立一個 |