我有一个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/