Apache Camel with Json Array split

笑着哭i 提交于 2019-12-01 14:57:40

You could try something like this:

@Override
protected RoutesBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {

        @Override
        public void configure() throws Exception {
            from("direct:start")
                .split().jsonpath("$")
                    .streaming()
                    .aggregate(AggregationStrategies.groupedExchange())
                    .constant("true")
                    .completionSize(5)
                    .completionTimeout(1000)
                    .log("${body}")
                .to("mock:result");
        }
    };
}

If the message doesn't have a size multiple of five, the route should wait 1 sec before aggregating and go ahead. Using your input, the result will be two messages with 5 and 3 items respectively:

INFO 5419 --- [           main] route1                                   : List<Exchange>(5 elements)
INFO 5419 --- [eTimeoutChecker] route1                                   : List<Exchange>(3 elements) 

A full sample could be viewed in here.

EDIT:

As requested, a Spring DSL example:

<camel:route>
    <camel:from uri="direct:start" />
    <camel:split streaming="true">
        <camel:jsonpath>$</camel:jsonpath>
        <camel:aggregate completionSize="5"
            completionTimeout="1000" groupExchanges="true">
            <camel:correlationExpression>
                <camel:constant>true</camel:constant>
            </camel:correlationExpression>
            <camel:log message="${body}"></camel:log>
            <camel:to uri="mock:result"></camel:to>
        </camel:aggregate>
    </camel:split>
</camel:route>

This will work

@Autowired
@EndpointInject(uri = "direct://splitted-queue")
ProducerTemplate producerTemplate;

@Component
  class Router extends RouteBuilder {

    @Override
    public void configure() throws Exception {
      from("direct://direct-queue").split(ExpressionBuilder.languageExpression("jsonpath","$")).convertBodyTo(String.class).process(new Processor() {
        List<String> jsons = new ArrayList<>();

        @Override
        public void process(Exchange exchange) throws Exception {
          jsons.add(exchange.getIn().getBody().toString());
          if(jsons.size() == 5) {
            producerTemplate.sendBody(jsons);
            jsons.clear();
          }
        }
      });
    }  

You need camel-jsonpath dependency for this

    <dependency>
        <groupId>org.apache.camel</groupId>
        <artifactId>camel-jsonpath</artifactId>
        <version>2.19.0</version>
    </dependency>

Try this

from("{{queue.endpoint}}")

.split().tokenize("},", 5)

.log("Incoming request : ${body} ")

;

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!