重试整批作业n次

时间:2015-03-24 05:49:55

标签: spring spring-batch

是否可以重试某项特定工作n次?

public void run() {

    String[] springConfig = { "spring/batch/jobs/job-read-files.xml" };
    ApplicationContext context = new ClassPathXmlApplicationContext(springConfig);

    JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher");
    Job job = (Job) context.getBean("partitionJob");
    JobParameters jobParameters = new JobParameters();
    for (int i = 0; i < 2; i++) {
        try {
            JobExecution execution = jobLauncher.run(job,jobParameters);
            System.out.println("Exit Status : " + execution.getAllFailureExceptions());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    System.out.println("Done");

}

我试过这个,但是由于春季批量存储了一些工作完成状态,所以它在第二次和第三次都没有工作。

更新:当我尝试这个时它起作用了

public void run() {
    for (int i = 0; i <= 2; i++) {
    String[] springConfig = { "spring/batch/jobs/job-read-files.xml" };
    ApplicationContext context = new ClassPathXmlApplicationContext(springConfig);

    JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher");
    Job job = (Job) context.getBean("partitionJob");
    JobParameters jobParameters = new JobParameters();

        try {
            JobExecution execution = jobLauncher.run(job,jobParameters);
            System.out.println("Exit Status : " + execution.getAllFailureExceptions());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    System.out.println("Done");

}

有比这更好的解决方案吗? 这是我的工作配置

<!-- partitioner job -->
<job id="partitionJob" restartable="true"  xmlns="http://www.springframework.org/schema/batch">
    <!-- master step, 2 threads (grid-size) -->
    <step id="masterStep" next="finalstep">
            <partition step="slave" partitioner="rangePartitioner">
                <handler grid-size="2" task-executor="taskExecutor" />
            </partition>
    </step>
    <step id="finalstep">
        <tasklet>
            <chunk reader="dummyReader" writer="spWriter" commit-interval="1" />
        </tasklet>
    </step>
</job>

<batch:step id="slave">
    <tasklet>
        <chunk reader="pagingItemReader" writer="dummyWriter"
            commit-interval="2" retry-limit="3">
            <batch:retryable-exception-classes>
                <batch:include class="java.lang.Exception" />
            </batch:retryable-exception-classes>
        </chunk>
    </tasklet>
</batch:step>

1 个答案:

答案 0 :(得分:1)

Spring具有很好的重试机制,您可以在其中定义RetryTemplate,并且您可以调用代码的某些部分N次,并且您可以定义RetryCallbackRecoveryCallback不错。

Spring批处理实际上在内部使用它来执行步骤中的重试机制。您可以结帐spring retry documentation并在步骤this is nice blog post上重试,这解释了春季批次中的跳过和重试机制。