Java Reference
In-Depth Information
Listing 4-50.
Basic Retry Configuration
<job id="flowJob">
<step id="retryStep">
<tasklet>
<chunk reader="itemReader" writer="itemWriter"
processor="itemProcessor" commit-interval="20"
retry-limit="3">
<retryable-exception-classes>
<include
class="org.springframework.remoting.RemoteAccessException"/>
</retryable-exception-classes>
</chunk>
</tasklet>
</step>
</job>
In the
flowJob
's
retryStep
, when a
RemoteAccessException
is thrown by any of the components in
the step (
itemReader
,
itemWriter
, or
itemProcessor
) the item is retried up to three times before the step
fails.
Another way to add retry logic to your batch job is to do it yourself via
org.springframework.batch.retry.RetryTemplate
. Like most other templates provided in Spring, this
one simplifies the development of retry logic by providing a simple API to encapsulate the retryable logic
in a method that is then managed by Spring. In the case of
RetryTemplate
, you need to develop two
pieces: the
org.springframework.batch.retry.RetryPolicy
interface and the
org.springframework.batch.retry.RetryCallback
interface.
RetryPolicy
allows you to define under
what conditions an item's processing is to be retried. Spring provides a number of implementations,
including ones for retrying based on an exception being thrown (which you used by default in Listing 4-
50), timeout, and others. The other piece of coding retry logic is the use of the
RetryCallback
interface.
This interface provides a single method,
doWithRetry(RetryContext context)
, that encapsulates the
logic to be retried. When you use
RetryTemplate
, if an item is to be retried, the
doWithRetry
method is
called as long as
RetryPolicy
specifies it to be. Let's look at an example.
Listing 4-51 shows the code to retry a call to a database with a timeout policy of 30 seconds. This
means it will continue to try executing the database call until it works or until 30 seconds has passed.
Listing 4-51.
Using
RetryTemplate
and
RetryCallback
package com.apress.springbatch.chapter4;
import java.util.List;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.retry.support.RetryTemplate;
import org.springframework.batch.retry.RetryCallback;
import org.springframework.batch.retry.RetryContext;
public class RetryItemWriter implements ItemWriter<Customer> {
private CustomerDAO customerDao;
private RetryTemplate retryTemplate;
public void write(List<? extends Customer> customers) throws Exception {