如何将多个编组(json)对象聚合到一个文件

时间:2014-11-17 13:59:48

标签: apache-camel aggregate

我创建了一个缓存/存储封送对象(json)到文件中的路由。此路由(以及读取缓冲区的其他路径)工作正常。 存储在缓冲区中:

from(DIRECT_IN).marshal().json().marshal().gzip().to(fileTarget()); 

从缓冲区读取:

from(fileTarget()).unmarshal().gzip().unmarshal().json().to("mock:a")

要减少i / o,我想在一个文件中聚合多个交换。我试着在json和之前聚合,所以我在json()之后或者从(...)之后添加它:

.aggregate(constant(true)).completionSize(20).completionTimeout(1000).groupExchanges()

在这两种情况下,我都会获得转换异常。怎么做正确?我更喜欢没有自定义聚合器的方法。如果只有很多交换/对象聚合在一个json(作为对象列表)或一个文本文件中 - 每行一个json对象,那就太好了。

提前致谢。

1 个答案:

答案 0 :(得分:-1)

与此同时,我添加了一个简单的聚合器:

public class LineAggregator implements AggregationStrategy {

@Override
public final Exchange aggregate(final Exchange oldExchange, final Exchange newExchange) {
    //if first message of aggregation
    if (oldExchange == null) {
        return newExchange;
    }
    //else aggregate
    String oldBody = oldExchange.getIn().getBody(String.class);
    String newBody = newExchange.getIn().getBody(String.class);
    String aggregate = oldBody + System.lineSeparator() + newBody;
    oldExchange.getIn().setBody(aggregate);
    return oldExchange;
}

}

路线看起来像是缓冲:

from(...)// marshal objects to json
                   .marshal()
                   .json()
                   .aggregate(constant(true), lineAggregator)
                   .completionSize(BUFFER_PACK_SIZE)
                   .completionTimeout(BUFFER_PACK_TIMEOUT)
                   .marshal()
                   .gzip()
                   .to(...)

来自缓冲区:

from(...).unmarshal()
                    .gzip()
                    .split()
                    .tokenize("\r\n|\n|\r")
                    .unmarshal()
                    .json()
                    .to(....)  

但问题仍然存在,聚合器是否必要?