Spring Integration Scatter-Gather流程无法打印Reply Channel消息问题求助
嘿,我仔细瞅了你的代码和问题描述,立马就找到症结了——你的flow3里用了split拆分消息,但没做聚合操作,导致Gatherer永远凑不齐3条完整的流结果,自然不会把消息发到Reply Channel。
问题根源拆解:
当你只跑两个GET流的时候,每个流都只会输出1条响应消息,Gatherer的释放条件能正常满足。但加了flow3后,你把释放条件设成了size==3,可flow3里的split会把payload.employee拆分成多条消息,每条都去发POST请求,最终flow3会向Gatherer发送N条消息(N是employee的数量),而不是1条。这样消息组的大小就变成了2 + N,永远大于3,Gatherer就一直卡着不释放,Reply Channel当然没东西给你打印。
一步到位的解决方案:
在flow3的POST请求处理完之后,加个aggregate聚合器,把split出来的所有POST响应合并成一条消息。这样flow3就只会给Gatherer发1条聚合后的结果,三个流刚好各贡献1条,满足size==3的释放条件。
修改后的flow3代码:
@Bean public IntegrationFlow flow3(){ return integrationFlowDefinition -> integrationFlowDefinition .channel(c -> c.executor(Executors.newCachedThreadPool())).log() .split("payload.employee").log() .enrichHeaders(h->h.header("ContentType", "application/json")).log() .handle(Http.outboundGateway("http://localhost:8888/Employee") .httpMethod(HttpMethod.POST) .expectedResponseType(String.class) .get()).log() // 新增聚合器,把split后的多个POST响应打包成一个列表 .aggregate() .log("已聚合POST请求结果: "); }
额外优化小技巧:
为了让返回的结果更清晰,你可以给Gatherer加个outputProcessor,把三个流的结果整理成结构化的数据:
scatterGather( scatterer -> scatterer .applySequence(true) .recipientFlow(flow1()) .recipientFlow(flow2()) .recipientFlow(flow3()), gatherer -> gatherer .releaseStrategy(group -> group.size()==3) .outputProcessor(group -> { List<Object> results = group.getMessages() .stream() .map(msg -> msg.getPayload()) .collect(Collectors.toList()); return Map.of( "GET接口1结果", results.get(0), "GET接口2结果", results.get(1), "POST接口聚合结果", results.get(2) ); }) )
这样你的网关返回的就是一个键值对清晰的Map,打印出来一目了然,比原始的Message列表友好多了。
另外,你的网关方法messages的返回值List<Message>可以改成Object或者自定义的结果DTO,这样更贴合实际返回的内容。
改完之后重启应用,你就能看到控制台正常打印出所有流的结果啦!
内容的提问来源于stack exchange,提问作者Somnath Mukherjee

