基于Spring的Camel Aggregator读取多个文件

时间:2016-12-02 00:08:05

标签: spring apache-camel

问题陈述

我有两个文件File1和File2需要使用camel Bindy进行解析。 需要聚合File1和File2中的数据,然后将其插入数据库。

定义agregator的最佳方法是,有人可以提供示例实现

这就是我想要的

<!--route1 -->
<route>
    <from ref="file1Endpoint" />
    <unmarshal ref="pojo1" />
</route>
<!--route2 -->
<route>
    <from ref="file2Endpoint" />
    <unmarshal ref="pojo2" />
</route>

1 个答案:

答案 0 :(得分:0)

使用提供Aggregation Strategy的{​​{3}},如下所示:

@Component
MyAggregationStrategy implements AggregationStrategy {

   public static final String PRE_ENRICH_KEY = "PRE_ENRICH_KEY";

   //this is meant to be called *before* the actual enrich call
   //to store the state before the enrichment
   public void init(Exchange exchange) {
     final String originalBody = exchange.getIn().getBody(String.class);
     exchange.setProperty(PRE_ENRICH_KEY, originalBody);
   }

   @Override
  public Exchange aggregate(Exchange original, Exchange enrichmentResponse) {

    final String originalBody = original.getProperty(PRE_ENRICH_KEY, String.class);

    //enrichmentResponse is the Exchange coming from the 2nd file endpoint
    //the enricher returns

    //your processing logic to merge the 2 happens here
    String result = //..
    original.getIn().setBody(result);

    return original;

  }

}

最后路线看起来像是:

@Component
public class MyRouteBuilder extends RouteBuilder {

    @Autowired
    private MyAggregationStrategy myAggregateStrategy;

    @Override
    public void configure() throws Exception {
        from("fileEndpoint1")
            .bean(myAggregateStrategy, "init")
            .enrich("fileEndpoint2", myMerger);
            //continue from here one to Bindy
    }

    //..
}