I tried the spring batch retry in this example. Retry feature is not working in Spring Batch and it works. I am trying to achieve the same with retrytemplate, but couldn't see the retry not working when thrown exception.
@Configuration
@EnableBatchProcessing
//@EnableRetry
public class RetryBatchJob {
@Autowired
private JobBuilderFactory jobs;
@Autowired
private StepBuilderFactory steps;
@Bean
public ItemReader<Integer> itemReader() {
return new ListItemReader<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
}
@Bean
public ItemWriter<Integer> itemWriter() {
return items -> {
for (Integer item : items) {
System.out.println("item = " + item);
if (item.equals(7)) {
throw new Exception("Sevens are sometime nasty, let's retry them");
}
}
};
}
@Bean
public Step step() {
return steps.get("step")
.<Integer, Integer>chunk(2)
.reader(itemReader())
.writer(itemWriter())
/*.faultTolerant()
.retryLimit(5)
.retry(Exception.class)*/
.build();
}
@Bean
public Job job() {
Job job = null;
try {
job = retryTemplate().execute(new RetryCallback<Job, Throwable>() {
@Override
public Job doWithRetry(RetryContext context) throws Throwable {
return jobs.get("job")
.start(step())
.build();
}
});
} catch (Throwable throwable) {
throwable.printStackTrace();
}
return job;
}
public static void main(String[] args) throws Exception {
ApplicationContext context = new AnnotationConfigApplicationContext(RetryBatchJob.class);
JobLauncher jobLauncher = context.getBean(JobLauncher.class);
Job job = context.getBean(Job.class);
jobLauncher.run(job, new JobParameters());
}
@Bean
public RetryTemplate retryTemplate() {
RetryTemplate retryTemplate = new RetryTemplate();
SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy(5, singletonMap(Exception.class, true));
retryPolicy.setMaxAttempts(5);
retryTemplate.setRetryPolicy(retryPolicy);
return retryTemplate;
}
}
Am I missing something when I use RetryTemplate? I tried declarative configuration on step and job methods too, but no luck.
@Retryable(value = {Exception.class},
maxAttemptsExpression = "5"
)
Note: using spring-retry 1.2.2 RELEASE.