Class RetryTemplate
- All Implemented Interfaces:
RetryOperations
Retryable operations are encapsulated in implementations of the RetryCallback
interface and are executed using one of the supplied execute methods.
By default, an operation is retried if is throws any Exception or subclass of
Exception. This behaviour can be changed by using the
setRetryPolicy(RetryPolicy) method.
Also by default, each operation is retried for a maximum of three attempts with no back
off in between. This behaviour can be configured using the
setRetryPolicy(RetryPolicy) and setBackOffPolicy(BackOffPolicy)
properties. The BackOffPolicy controls how
long the pause is between each individual retry attempt.
A new instance can be fluently configured via builder(), e.g:
RetryTemplate.builder()
.maxAttempts(10)
.fixedBackoff(1000)
.build();
See RetryTemplateBuilder for more examples and details.
This class is thread-safe and suitable for concurrent access when executing operations
and when performing configuration changes. As such, it is possible to change the number
of retries on the fly, as well as the BackOffPolicy used and no in progress
retryable operations will be affected.
- Author:
- Rob Harrop, Dave Syer, Gary Russell, Artem Bilan, Josh Long, Aleksandr Shamukov, Emanuele Ivaldi, Tobias Soloschenko
-
Field Summary
Fields -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionstatic RetryTemplateBuilderbuilder()Main entry point to configure RetryTemplate using fluent API.protected booleancanRetry(RetryPolicy retryPolicy, RetryContext context) Decide whether to proceed with the ongoing retry attempt.protected voidclose(RetryPolicy retryPolicy, RetryContext context, RetryState state, boolean succeeded) Clean up the cache if necessary and close the context provided (if the flag indicates that processing was successful).static RetryTemplateCreates a new default instance.protected <T,E extends Throwable>
TdoExecute(RetryCallback<T, E> retryCallback, RecoveryCallback<T> recoveryCallback, RetryState state) Execute the callback once if the policy dictates that we can, otherwise execute the recovery callback.final <T,E extends Throwable>
Texecute(RetryCallback<T, E> retryCallback) Keep executing the callback until it either succeeds or the policy dictates that we stop, in which case the most recent exception thrown by the callback will be rethrown.final <T,E extends Throwable>
Texecute(RetryCallback<T, E> retryCallback, RecoveryCallback<T> recoveryCallback) Keep executing the callback until it either succeeds or the policy dictates that we stop, in which case the recovery callback will be executed.final <T,E extends Throwable>
Texecute(RetryCallback<T, E> retryCallback, RecoveryCallback<T> recoveryCallback, RetryState retryState) Execute the callback once if the policy dictates that we can, re-throwing any exception encountered so that clients can re-present the same task later.final <T,E extends Throwable>
Texecute(RetryCallback<T, E> retryCallback, RetryState retryState) Execute the callback once if the policy dictates that we can, re-throwing any exception encountered so that clients can re-present the same task later.protected <T> ThandleRetryExhausted(RecoveryCallback<T> recoveryCallback, RetryContext context, RetryState state) Actions to take after final attempt has failed.booleanReturn true if at least one listener is registered.protected RetryContextopen(RetryPolicy retryPolicy, RetryState state) Delegate to theRetryPolicyhaving checked in the cache for an existing value if the state is not null.voidregisterListener(RetryListener listener) Register an additional listener at the end of the list.voidregisterListener(RetryListener listener, int index) Register an additional listener at the specified index.protected voidregisterThrowable(RetryPolicy retryPolicy, RetryState state, RetryContext context, Throwable e) protected <E extends Throwable>
voidrethrow(RetryContext context, String message, boolean wrap) voidsetBackOffPolicy(BackOffPolicy backOffPolicy) Setter forBackOffPolicy.voidsetListeners(RetryListener[] listeners) Setter for listeners.voidsetLogger(org.apache.commons.logging.Log logger) Setter forLog.voidsetRetryContextCache(RetryContextCache retryContextCache) Public setter for theRetryContextCache.voidsetRetryPolicy(RetryPolicy retryPolicy) Setter forRetryPolicy.voidsetThrowLastExceptionOnExhausted(boolean throwLastExceptionOnExhausted) Whether to re-throw last exception or wrap intoExhaustedRetryExceptionwhen all retry attempts are exhausted.protected booleanshouldRethrow(RetryPolicy retryPolicy, RetryContext context, RetryState state) Extension point for subclasses to decide on behaviour after catching an exception in aRetryCallback.
-
Field Details
-
logger
protected org.apache.commons.logging.Log logger
-
-
Constructor Details
-
RetryTemplate
public RetryTemplate()
-
-
Method Details
-
builder
Main entry point to configure RetryTemplate using fluent API. SeeRetryTemplateBuilderfor usage examples and details.- Returns:
- a new instance of RetryTemplateBuilder with preset default behaviour, that can be overwritten during manual configuration
- Since:
- 1.3
-
defaultInstance
Creates a new default instance. The properties of default instance are described inRetryTemplateBuilderdocumentation.- Returns:
- a new instance of RetryTemplate with default behaviour
- Since:
- 1.3
-
setThrowLastExceptionOnExhausted
public void setThrowLastExceptionOnExhausted(boolean throwLastExceptionOnExhausted) Whether to re-throw last exception or wrap intoExhaustedRetryExceptionwhen all retry attempts are exhausted. Defaults tofalse; applied only in case of supplied state, e.g.StatefulRetryOperationsInterceptor.- Parameters:
throwLastExceptionOnExhausted- the throwLastExceptionOnExhausted to set
-
setRetryContextCache
Public setter for theRetryContextCache.- Parameters:
retryContextCache- theRetryContextCacheto set.
-
setListeners
Setter for listeners. The listeners are executed before and after a retry block (i.e. before and after all the attempts), and on an error (every attempt).- Parameters:
listeners- theRetryListeners- See Also:
-
registerListener
Register an additional listener at the end of the list.- Parameters:
listener- theRetryListener- See Also:
-
registerListener
Register an additional listener at the specified index.- Parameters:
listener- theRetryListenerindex- the position in the list.- Since:
- 1.3
- See Also:
-
hasListeners
public boolean hasListeners()Return true if at least one listener is registered.- Returns:
- true if listeners present.
- Since:
- 1.3
-
setLogger
public void setLogger(org.apache.commons.logging.Log logger) Setter forLog. If not applied the following is used:LogFactory.getLog(getClass())- Parameters:
logger- the logger the retry template uses for logging- Since:
- 2.0.10
-
setBackOffPolicy
Setter forBackOffPolicy.- Parameters:
backOffPolicy- theBackOffPolicy
-
setRetryPolicy
Setter forRetryPolicy.- Parameters:
retryPolicy- theRetryPolicy
-
execute
Keep executing the callback until it either succeeds or the policy dictates that we stop, in which case the most recent exception thrown by the callback will be rethrown.- Specified by:
executein interfaceRetryOperations- Type Parameters:
T- the return valueE- the exception to throw- Parameters:
retryCallback- theRetryCallback- Returns:
- the value returned by the
RetryCallbackupon successful invocation. - Throws:
TerminatedRetryException- if the retry has been manually terminated by a listener.E- anyExceptionraised by theRetryCallbackupon unsuccessful retry.- See Also:
-
execute
public final <T,E extends Throwable> T execute(RetryCallback<T, E> retryCallback, RecoveryCallback<T> recoveryCallback) throws EKeep executing the callback until it either succeeds or the policy dictates that we stop, in which case the recovery callback will be executed.- Specified by:
executein interfaceRetryOperations- Type Parameters:
T- the type to returnE- the type of the exception- Parameters:
retryCallback- theRetryCallbackrecoveryCallback- theRecoveryCallback- Returns:
- the value returned by the
RetryCallbackupon successful invocation, and that returned by theRecoveryCallbackotherwise. - Throws:
TerminatedRetryException- if the retry has been manually terminated by a listener.E- anyExceptionraised by the unsuccessful retry.- See Also:
-
execute
public final <T,E extends Throwable> T execute(RetryCallback<T, E> retryCallback, RetryState retryState) throws E, ExhaustedRetryExceptionExecute the callback once if the policy dictates that we can, re-throwing any exception encountered so that clients can re-present the same task later.- Specified by:
executein interfaceRetryOperations- Type Parameters:
T- the type of the return valueE- the type of the exception to return- Parameters:
retryCallback- theRetryCallbackretryState- theRetryState- Returns:
- the value returned by the
RetryCallbackupon successful invocation, and that returned by theRecoveryCallbackotherwise. - Throws:
ExhaustedRetryException- if the retry has been exhausted.E- anyExceptionraised by theRecoveryCallback.- See Also:
-
execute
public final <T,E extends Throwable> T execute(RetryCallback<T, E> retryCallback, RecoveryCallback<T> recoveryCallback, RetryState retryState) throws E, ExhaustedRetryExceptionExecute the callback once if the policy dictates that we can, re-throwing any exception encountered so that clients can re-present the same task later.- Specified by:
executein interfaceRetryOperations- Type Parameters:
T- the return value typeE- the exception type- Parameters:
retryCallback- theRetryCallbackrecoveryCallback- theRecoveryCallbackretryState- theRetryState- Returns:
- the value returned by the
RetryCallbackupon successful invocation, and that returned by theRecoveryCallbackotherwise. - Throws:
E- anyExceptionraised by theRecoveryCallbackupon unsuccessful retry.ExhaustedRetryException- See Also:
-
doExecute
protected <T,E extends Throwable> T doExecute(RetryCallback<T, E> retryCallback, RecoveryCallback<T> recoveryCallback, RetryState state) throws E, ExhaustedRetryExceptionExecute the callback once if the policy dictates that we can, otherwise execute the recovery callback.- Type Parameters:
T- the type of the return valueE- the exception type to throw- Parameters:
recoveryCallback- theRecoveryCallbackretryCallback- theRetryCallbackstate- theRetryState- Returns:
- T the retried value
- Throws:
ExhaustedRetryException- if the retry has been exhausted.E- an exception if the retry operation fails- See Also:
-
canRetry
Decide whether to proceed with the ongoing retry attempt. This method is called before theRetryCallbackis executed, but after the backoff and open interceptors.- Parameters:
retryPolicy- the policy to applycontext- the current retry context- Returns:
- true if we can continue with the attempt
-
close
protected void close(RetryPolicy retryPolicy, RetryContext context, RetryState state, boolean succeeded) Clean up the cache if necessary and close the context provided (if the flag indicates that processing was successful).- Parameters:
retryPolicy- theRetryPolicycontext- theRetryContextstate- theRetryStatesucceeded- whether the close succeeded
-
registerThrowable
protected void registerThrowable(RetryPolicy retryPolicy, RetryState state, RetryContext context, Throwable e) -
open
Delegate to theRetryPolicyhaving checked in the cache for an existing value if the state is not null.- Parameters:
state- aRetryStateretryPolicy- aRetryPolicyto delegate the context creation- Returns:
- a retry context, either a new one or the one used last time the same state was encountered
-
handleRetryExhausted
protected <T> T handleRetryExhausted(RecoveryCallback<T> recoveryCallback, RetryContext context, RetryState state) throws Throwable Actions to take after final attempt has failed. If there is state clean up the cache. If there is a recovery callback, execute that and return its result. Otherwise, throw an exception.- Type Parameters:
T- the type to classify- Parameters:
recoveryCallback- the callback for recovery (might be null)context- the current retry contextstate- theRetryState- Returns:
- T the payload to return
- Throws:
Exception- if the callback does, and if there is no callback and the state is null then the last exception from the contextExhaustedRetryException- if the state is not null and there is no recovery callbackThrowable- if there is an error
-
rethrow
protected <E extends Throwable> void rethrow(RetryContext context, String message, boolean wrap) throws E - Throws:
E extends Throwable
-
shouldRethrow
Extension point for subclasses to decide on behaviour after catching an exception in aRetryCallback. Normal stateless behaviour is not to rethrow, and if there is state we rethrow.- Parameters:
retryPolicy- the retry policycontext- the current contextstate- the current retryState- Returns:
- true if the state is not null but subclasses might choose otherwise
-