Mule - split a big JSON list into multiple smaller JSON lists

强颜欢笑 提交于 2019-12-13 12:22:07

问题


I have a list of json objects containing about 200 objects. I want to split that list into smaller lists where each list contains max 20 objects each. I would like to POST each sublist to HTTP based endpoint.

<flow name="send-to-next-step" doc:name="send-to-vm-flow">
    <vm:inbound-endpoint exchange-pattern="one-way"
        path="send-to-next-step-vm" doc:name="VM" />
    <!-- received the JSON List payload with 200 objects-->
    <!-- TODO do processing here to split the list into sub-lists and call sub-flow for each sub-list
    <flow-ref name="send-to-aggregator-sf" doc:name="Flow Reference" />
</flow>

One possible way is that I write a java component which iterates over the list and after iterating over each 20 objects, call sub-flow. Is there any better way of accomplishing this?


回答1:


If your payload is a Java Collection, the Mule foreach scope has batching built in: http://www.mulesoft.org/documentation/display/current/Foreach

Example:

<foreach batchSize="20">
   <json:object-to-json-transformer/>
   <http:outbound-endpoint ... />
</foreach>



回答2:


You could use the Groovy collate method for the batching, and then foreach or collection-splitter, depending on your needs:

<json:json-to-object-transformer returnClass="java.util.List"/>
<set-payload value="#[groovy:payload.collate(20)]"/>
<foreach>
   <json:object-to-json-transformer/>
   <http:outbound-endpoint exchange-pattern="request-response" host="0.0.0.0" port="8082" path="xx"/>
</foreach>
<set-payload value="#[groovy:payload.flatten()]"/>

This will send each batch of 20 objects to the http endpoint and then flatten back to the original list.



来源:https://stackoverflow.com/questions/22189150/mule-split-a-big-json-list-into-multiple-smaller-json-lists

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