Spring Batch-Repeat step for each item in a data list

橙三吉。 提交于 2019-12-04 13:00:05

Yes, check out the partitioning feature of spring-batch! http://static.springsource.org/spring-batch/reference/html-single/index.html#partitioning

Basically, it allows you to use a "partitioner" to create new execution contexts to pass to a handler that then does something with that information.

While partitioning was made for parallelization, its default concurrency is 1, so you can start small and ratchet it up to match the hardware at your disposal. Since I assume that each country's data is not dependent on the others (at least in the download demographics step), your job could make use of basic parallelization.

/EDIT: Adding example.

Here's what I do (more or less): First, the XML:

<beans>
  <batch:job id="jobName">
    <batch:step id="innerStep.master">
      <batch:partition partitioner="myPartitioner" step="innerStep"/>
    </batch:step>
  </batch:job>
  <bean id="myPartitioner" class="org.lapseda.MyPartitioner" scope="step">
    <property name="jdbcTemplate" ref="jdbcTemplate"/>
    <property name="runDate" value="#{jobExecutionContext['runDate']}"/>
    <property name="recurrenceId" value="D"/>
  </bean>
  <batch:step id="summaryDetailsReportStep">
    <batch:tasklet>
      <batch:chunk reader="someReader" processor="someProcessor" writer="someWriter" commit-interval="10"/>
    </batch:tasklet>
  </batch:step>
</beans>

And now some Java:

public class MyPartitioner implements Partitioner {
  @Override 
  public Map<String, ExecutionContext> partition(int gridSize) {
    List<String> list = getValuesToRunOver();
    /* I use treemap because my partitions are ordered, hashmap should work if order isn't important */
    Map<String, ExecutionContext> out = new TreeMap<String, ExecutionContext>(); 
    for (String item : list) {
      ExecutionContext context = new ExecutionContext();
      context.put("key", "value"); // add your own stuff!
      out.put("innerStep"+item, context);
    }
    return out;
  }
}

Then you just read from the context like you would from a normal step or job context inside your step.

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