简体   繁体   中英

Spring retry policy for connection and read timeouts

I have a spring boot application where I have implemented a rest template and have set connection and read timeouts. I am trying to implement a retry policy for the application retry when these timeouts are executing. When the timeouts are occurring, the connection and read timeouts are throwing ResourceAccessException. Further into the details for each timeouts, the connection timeout is showing a ConnectionTimeoutException and the read timeout is showing a SocketTimeoutException. I have implemented a RetryTemplate, shown below, to execute a certain number of times and need assitance with executing it with retries for these time out exceptions. Any advice would be greatly appreciated. Thanks!!

       @Bean
            public RetryTemplate retryTemplate() {
                SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
                retryPolicy.setMaxAttempts(maxAttempts);

                FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();
                backOffPolicy.setBackOffPeriod(backOffPeriod);

                RetryTemplate template = new RetryTemplate();
                template.setRetryPolicy(retryPolicy);
                template.setBackOffPolicy(backOffPolicy);

                return template;
            }


    public class RetryService {
    @Autowired
    private RetryTemplate retryTemplate;

    public class RetryService {
    @Autowired
    private RetryTemplate retryTemplate;

    public void withTemplate() {
        retryTemplate.execute(retryContext -> {

        });
    }
}

You can use one of the advanced retry policies (read their javadocs).

Or, simply configure the SimpleRetryPolicy with one of its richer constructors, such as this one .

/**
 * Create a {@link SimpleRetryPolicy} with the specified number of retry attempts. If
 * traverseCauses is true, the exception causes will be traversed until a match is
 * found. The default value indicates whether to retry or not for exceptions (or super
 * classes) are not found in the map.
 * @param maxAttempts the maximum number of attempts
 * @param retryableExceptions the map of exceptions that are retryable based on the
 * map value (true/false).
 * @param traverseCauses is this clause traversable
 * @param defaultValue the default action.
 */
public SimpleRetryPolicy(int maxAttempts, Map<Class<? extends Throwable>, Boolean> retryableExceptions,
        boolean traverseCauses, boolean defaultValue) {

Configure the map with the exceptions you want retried.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM