如何使用聚合器附加Exchange标头

时间:2018-02-20 06:32:28

标签: java spring-boot apache-camel append

我正在编写一个聚合策略类,我需要旧交换的头文件,并且应该相互附加新的交换,以便将集合头传递给下一个处理器类。

我尝试了putAll newHeader,但它没有附加到旧交易所。

Map<String, Object> newHeader = newExchange.getIn().getHeaders();
oldExchange.getIn().getHeaders().putAll(newHeader);
return oldExchange;

有什么建议吗?我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:0)

public class AggregateHeaders implements AggregationStrategy {
@Override
public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
    Map<String, Object> newHeaders = newExchange.getIn().getHeaders();
    oldExchange.getIn().getHeaders().putAll(newHeaders);
    return oldExchange;
}}

您的代码应按预期工作......

写了一个小测试

@Test
public void test() {
    DefaultCamelContext context = new DefaultCamelContext();
    AggregateHeaders aggregator = new AggregateHeaders();
    DefaultExchange newExchange = new DefaultExchange(context);
    newExchange.getIn().setHeader("newName", "newValue");
    DefaultExchange oldExchange = new DefaultExchange(context);
    oldExchange.getIn().setHeader("oldName", "oldValue");
    Exchange aggregated = aggregator.aggregate(oldExchange, newExchange);
    assertThat(aggregated.getIn().getHeader("oldName"), is("oldValue"));
    assertThat(aggregated.getIn().getHeader("newName"), is("newValue"));
}

另见https://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/Message.html#setHeaders(java.util.Map)

  

重要提示:如果您要将其他消息中的标题复制到此消息,请使用 getHeaders()。putAll(其他)复制标题,其他标题是其他标题。