java - 用于连接和读取超时的Spring重试策略

标签 java spring connection-timeout spring-retry socket-timeout-exception

我有一个Spring Boot应用程序,其中实现了rest模板,并设置了连接和读取超时。这些超时正在执行时,我正在尝试为应用程序重试实施重试策略。发生超时时,连接和读取超时将引发ResourceAccessException。在每个超时的详细信息中,连接超时显示ConnectionTimeoutException,而读取超时显示SocketTimeoutException。我已经实现了一个RetryTemplate(如下所示),以执行一定次数,并且需要协助以重试的方式执行这些超时异常。任何建议将不胜感激。谢谢!!

       @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 -> {

        });
    }
}

最佳答案

您可以使用advanced retry policies之一(请阅读其javadocs)。

或者,只需使用其更丰富的构造函数之一(例如this one)配置SimpleRetryPolicy

/**
 * 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) {


使用要重试的异常配置映射。

关于java - 用于连接和读取超时的Spring重试策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58383176/

相关文章:

java - 拖放 JTableHeader

java - 使用 selenium 库在本地替换网站上的图像

java - 使用 Spring Batch 进行事务管理

java - 注入(inject)静态属性值

Spring JTA 事务管理器问题

javascript - 浏览器超时 : the server at example. com 响应时间太长

java - Android 在线流媒体应用程序不应在屏幕锁定和解锁时关闭

java负向后看正则表达式错误?

android - 如何防止 Android 中可怕的 KSOAP2 连接超时

android - HttpClient 执行不断给出 ConnectTimeoutException