我在我的 Spring Boot 应用程序中集成了一个休息模板。其余模板成功建立连接并读取超时。我还集成了一个重试模板来重试这些连接和读取超时。我的重试模板的代码如下。我的代码有问题,无法解决。任何见解都会非常有帮助。我的“回调”有一个错误,它指出它无法自动连接并且没有找到bean。对于“FAILED”,我收到无法解析符号。
@Bean
public RetryTemplate retryTemplate(RetryCallback<RetryTemplate, Exception> callback) {
RetryTemplate template = new RetryTemplate();
ExceptionClassifierRetryPolicy retryPolicy = new ExceptionClassifierRetryPolicy();
Map<Class<? extends Throwable>, Boolean> retryableExceptions = new HashMap<Class<? extends Throwable>, Boolean>();
retryableExceptions.put(SocketTimeoutException.class, Boolean.TRUE);
retryableExceptions.put(ConnectionPoolTimeoutException.class, Boolean.TRUE);
retryableExceptions.put(ResourceAccessException.class, Boolean.TRUE);
NeverRetryPolicy doNotRetry = new NeverRetryPolicy();
SimpleRetryPolicy simpleRetryPolicy = new SimpleRetryPolicy(maxAttempts, retryableExceptions);
simpleRetryPolicy.setMaxAttempts(maxAttempts);
FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();
backOffPolicy.setBackOffPeriod(backOffPeriod);
template.setRetryPolicy(simpleRetryPolicy);
template.setBackOffPolicy(backOffPolicy);
try {
return template.execute(callback);
} catch (Exception e) {
logger.error("Retry processing failed " + e.getMessage());
return RetryTemplate.FAILED;
}
}
最佳答案
@Bean
工厂方法只是一个 bean 定义;你不能像这样放置运行时代码
try {
return template.execute(callback);
} catch (Exception e) {
logger.error("Retry processing failed " + e.getMessage());
return RetryTemplate.FAILED;
}
那里。您必须返回模板;
。
由于您要将 RetryCallback
传递到工厂方法中,因此您必须在其他地方定义该类型的 @Bean
。
但是,回调是在运行时使用的,而不是在 bean 定义时使用。
然后,您可以在应用程序的其他位置使用 template.execute()
。
到底什么是RetryTemplate.FAILED
- 没有这样的常量。
关于java - 创建重试模板以在连接超时和读取超时时重试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58400392/