Vai*_*ibS 2 java spring java-8 spring-retry spring-boot
我正在使用spring-retry(带有Java 8 lambda)来重试失败的REST调用。我只想重试那些返回500错误的呼叫。但是我不能为此配置retrytemplate bean。当前,bean很简单,如下所示:
@Bean("restRetryTemplate")
public RetryTemplate retryTemplate() {
Map<Class<? extends Throwable>, Boolean> retryableExceptions= Collections.singletonMap(HttpServerErrorException.class,
Boolean.TRUE);
SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy(3, retryableExceptions);
FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();
backOffPolicy.setBackOffPeriod(1500); // 1.5 seconds
RetryTemplate template = new RetryTemplate();
template.setRetryPolicy(retryPolicy);
template.setBackOffPolicy(backOffPolicy);
return template;
}
Run Code Online (Sandbox Code Playgroud)
谁能帮我这个忙。提前致谢。
因此,我通过以下方式创建自定义RetryPolicy解决了我的问题:
RetryTemplate template = new RetryTemplate();
template.setRetryPolicy(new InternalServerExceptionClassifierRetryPolicy());
Run Code Online (Sandbox Code Playgroud)
实现如下:
public class InternalServerExceptionClassifierRetryPolicy extends ExceptionClassifierRetryPolicy {
public InternalServerExceptionClassifierRetryPolicy() {
final SimpleRetryPolicy simpleRetryPolicy = new SimpleRetryPolicy();
simpleRetryPolicy.setMaxAttempts(3);
this.setExceptionClassifier(new Classifier<Throwable, RetryPolicy>() {
@Override
public RetryPolicy classify(Throwable classifiable) {
if (classifiable instanceof HttpServerErrorException) {
// For specifically 500 and 504
if (((HttpServerErrorException) classifiable).getStatusCode() == HttpStatus.INTERNAL_SERVER_ERROR
|| ((HttpServerErrorException) classifiable)
.getStatusCode() == HttpStatus.GATEWAY_TIMEOUT) {
return simpleRetryPolicy;
}
return new NeverRetryPolicy();
}
return new NeverRetryPolicy();
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
希望这会对您有所帮助。
| 归档时间: |
|
| 查看次数: |
927 次 |
| 最近记录: |