gpt4 book ai didi

java - 如何在Camel中循环后访问聚合消息

转载 作者:太空宇宙 更新时间:2023-11-04 12:55:22 25 4
gpt4 key购买 nike

Camel 2.16.1 Loop 之后如何获取聚合消息?我得到的唯一输出是循环中处理的最后一条消息。

我的循环迭代了三次,并且有一个聚合器将主体组合在单个字符串中。循环如下所示:

from("timer:begin?repeatCount=1&delay=1")
.routeId("timer")
.to("direct:loop")
.log("Body after Loop Route: ${body}");

from("direct:loop")
.routeId("loop")
.loop(3)
.setBody().simple("Hello ${exchangeProperty.CamelLoopIndex}")
.log("Body in Loop: ${body}")
.aggregate(new AggregationStrategy() {

public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
if (oldExchange == null) {
return newExchange;
}
else {
String oldBody = oldExchange.getIn().getBody(String.class);
String newBody = oldBody + ", " + newExchange.getIn().getBody(String.class);
newExchange.getIn().setBody(newBody);
return newExchange;
}
}
}).constant(true).completionSize(3)
.log("Body after Aggregate: ${body}")
.end();

问题是在计时器路由中我无法访问聚合消息。相反,示例中的计时器路由输出Hello 2,如下所示:

Body in Loop: Hello 0
Body in Loop: Hello 1
Body in Loop: Hello 2
Body after Aggregate: Hello 0, Hello 1, Hello 2
Body after Loop Route: Hello 2

最佳答案

我不知道如何使用 Loop 来做到这一点。然而Camel网站上说Loop

Useful mostly during testing.

所以我走了另一条路。

因此,为了像循环一样迭代某些值并获取聚合结果,我修改了路线以使用 SplitterAggregator像这样

from("timer:begin?repeatCount=1&delay=1")
.routeId("timer")
.to("direct:splitter-loop")
.log("Body after Loop Route: ${body}");

from("direct:splitter-loop")
.routeId("splitter-loop")
.process(exchange -> {
// Add items that you want to iterate over to body or header
// and later use splitter over those items.
List<String> loopIndex = new ArrayList<String>();
loopIndex.add("1");
loopIndex.add("2");
loopIndex.add("3");
exchange.getOut().setBody(loopIndex);
})
.split(body(), new StringAggregator())
.setBody().simple("Hello ${body}")
.log("Body in Loop: ${body}")
.end()
.log("Body after Aggregate: ${body}");

其中 StringAggregator 与之前一样:

public class StringAggregator implements AggregationStrategy {

public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
if (oldExchange == null) {
return newExchange;
}
else {
String oldBody = oldExchange.getIn().getBody(String.class);
String newBody = oldBody + ", " + newExchange.getIn().getBody(String.class);
newExchange.getIn().setBody(newBody);
return newExchange;
}
}
}

这条路线现在给了我想要的聚合结果,如下所示

Body in Loop: Hello 1
Body in Loop: Hello 2
Body in Loop: Hello 3
Body after Aggregate: Hello 1, Hello 2, Hello 3
Body after Loop Route: Hello 1, Hello 2, Hello 3

关于java - 如何在Camel中循环后访问聚合消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35433179/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com