Class RetryTemplate

java.lang.Object
org.springframework.retry.support.RetryTemplate
All Implemented Interfaces:
RetryOperations

public class RetryTemplate extends Object implements RetryOperations
Template class that simplifies the execution of operations with retry semantics.

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 Details

    • logger

      protected org.apache.commons.logging.Log logger
  • Constructor Details

    • RetryTemplate

      public RetryTemplate()
  • Method Details

    • builder

      public static RetryTemplateBuilder builder()
      Main entry point to configure RetryTemplate using fluent API. See RetryTemplateBuilder for 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

      public static RetryTemplate defaultInstance()
      Creates a new default instance. The properties of default instance are described in RetryTemplateBuilder documentation.
      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 into ExhaustedRetryException when all retry attempts are exhausted. Defaults to false; applied only in case of supplied state, e.g. StatefulRetryOperationsInterceptor.
      Parameters:
      throwLastExceptionOnExhausted - the throwLastExceptionOnExhausted to set
    • setRetryContextCache

      public void setRetryContextCache(RetryContextCache retryContextCache)
      Public setter for the RetryContextCache.
      Parameters:
      retryContextCache - the RetryContextCache to set.
    • setListeners

      public void setListeners(RetryListener[] listeners)
      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 - the RetryListeners
      See Also:
    • registerListener

      public void registerListener(RetryListener listener)
      Register an additional listener at the end of the list.
      Parameters:
      listener - the RetryListener
      See Also:
    • registerListener

      public void registerListener(RetryListener listener, int index)
      Register an additional listener at the specified index.
      Parameters:
      listener - the RetryListener
      index - 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 for Log. 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

      public void setBackOffPolicy(BackOffPolicy backOffPolicy)
      Setter for BackOffPolicy.
      Parameters:
      backOffPolicy - the BackOffPolicy
    • setRetryPolicy

      public void setRetryPolicy(RetryPolicy retryPolicy)
      Setter for RetryPolicy.
      Parameters:
      retryPolicy - the RetryPolicy
    • execute

      public final <T, E extends Throwable> T execute(RetryCallback<T,E> retryCallback) throws E
      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:
      execute in interface RetryOperations
      Type Parameters:
      T - the return value
      E - the exception to throw
      Parameters:
      retryCallback - the RetryCallback
      Returns:
      the value returned by the RetryCallback upon successful invocation.
      Throws:
      TerminatedRetryException - if the retry has been manually terminated by a listener.
      E - any Exception raised by the RetryCallback upon unsuccessful retry.
      See Also:
    • execute

      public final <T, E extends Throwable> T execute(RetryCallback<T,E> retryCallback, RecoveryCallback<T> recoveryCallback) throws E
      Keep 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:
      execute in interface RetryOperations
      Type Parameters:
      T - the type to return
      E - the type of the exception
      Parameters:
      retryCallback - the RetryCallback
      recoveryCallback - the RecoveryCallback
      Returns:
      the value returned by the RetryCallback upon successful invocation, and that returned by the RecoveryCallback otherwise.
      Throws:
      TerminatedRetryException - if the retry has been manually terminated by a listener.
      E - any Exception raised by the unsuccessful retry.
      See Also:
    • execute

      public final <T, E extends Throwable> T execute(RetryCallback<T,E> retryCallback, RetryState retryState) throws E, ExhaustedRetryException
      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.
      Specified by:
      execute in interface RetryOperations
      Type Parameters:
      T - the type of the return value
      E - the type of the exception to return
      Parameters:
      retryCallback - the RetryCallback
      retryState - the RetryState
      Returns:
      the value returned by the RetryCallback upon successful invocation, and that returned by the RecoveryCallback otherwise.
      Throws:
      ExhaustedRetryException - if the retry has been exhausted.
      E - any Exception raised by the RecoveryCallback.
      See Also:
    • execute

      public final <T, E extends Throwable> T execute(RetryCallback<T,E> retryCallback, RecoveryCallback<T> recoveryCallback, RetryState retryState) throws E, ExhaustedRetryException
      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.
      Specified by:
      execute in interface RetryOperations
      Type Parameters:
      T - the return value type
      E - the exception type
      Parameters:
      retryCallback - the RetryCallback
      recoveryCallback - the RecoveryCallback
      retryState - the RetryState
      Returns:
      the value returned by the RetryCallback upon successful invocation, and that returned by the RecoveryCallback otherwise.
      Throws:
      E - any Exception raised by the RecoveryCallback upon unsuccessful retry.
      ExhaustedRetryException
      See Also:
    • doExecute

      protected <T, E extends Throwable> T doExecute(RetryCallback<T,E> retryCallback, RecoveryCallback<T> recoveryCallback, RetryState state) throws E, ExhaustedRetryException
      Execute the callback once if the policy dictates that we can, otherwise execute the recovery callback.
      Type Parameters:
      T - the type of the return value
      E - the exception type to throw
      Parameters:
      recoveryCallback - the RecoveryCallback
      retryCallback - the RetryCallback
      state - the RetryState
      Returns:
      T the retried value
      Throws:
      ExhaustedRetryException - if the retry has been exhausted.
      E - an exception if the retry operation fails
      See Also:
    • canRetry

      protected boolean canRetry(RetryPolicy retryPolicy, RetryContext context)
      Decide whether to proceed with the ongoing retry attempt. This method is called before the RetryCallback is executed, but after the backoff and open interceptors.
      Parameters:
      retryPolicy - the policy to apply
      context - 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 - the RetryPolicy
      context - the RetryContext
      state - the RetryState
      succeeded - whether the close succeeded
    • registerThrowable

      protected void registerThrowable(RetryPolicy retryPolicy, RetryState state, RetryContext context, Throwable e)
    • open

      protected RetryContext open(RetryPolicy retryPolicy, RetryState state)
      Delegate to the RetryPolicy having checked in the cache for an existing value if the state is not null.
      Parameters:
      state - a RetryState
      retryPolicy - a RetryPolicy to 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 context
      state - the RetryState
      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 context
      ExhaustedRetryException - if the state is not null and there is no recovery callback
      Throwable - 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

      protected boolean shouldRethrow(RetryPolicy retryPolicy, RetryContext context, RetryState state)
      Extension point for subclasses to decide on behaviour after catching an exception in a RetryCallback. Normal stateless behaviour is not to rethrow, and if there is state we rethrow.
      Parameters:
      retryPolicy - the retry policy
      context - the current context
      state - the current retryState
      Returns:
      true if the state is not null but subclasses might choose otherwise