我第一次使用Spring Retry。我正在尝试重试HTTP状态代码5 **。 我将以下问题作为参考,并尝试创建自己的自定义重试策略:
Spring Retry Junit: Testing Retry template with Custom Retry Policy
但是当我尝试执行RetryTemplate时,即使我将Maximum尝试次数设置为大于1,它也只会重试一次。请帮我解决此问题。在此先感谢!!!
@Bean("MyRetryTemplate")
public RetryTemplate myRetryTemplate() {
RetryTemplate retryTemplate = new RetryTemplate();
CustomRetryPolicy customRetryPolicy = new CustomRetryPolicy();
customRetryPolicy.setMaxAttempts(5);
retryTemplate.setRetryPolicy(customRetryPolicy);
return retryTemplate;
}
具有执行的服务类:
public class MyServiceImpl {
@Autowired
private RestTemplate restTemplate;
@Autowired
@Qualifier("MyRetryTemplate")
private RetryTemplate myRetryTemplate;
public List<Employee> getEmployees(){
// other code
try {
response = myRetryTemplate.execute(new
RetryCallback<ResponseEntity<String>, HttpStatusCodeException>() {
@Override
public ResponseEntity doWithRetry(RetryContext context) throws
HttpStatusCodeException {
System.out.println("Retrying ========================>");
ResponseEntity<String> responseRetry = restTemplate.exchange(Url,
HttpMethod.POST, entity,
new ParameterizedTypeReference<String>() {
});
return responseRetry;
}
});
//other code
} catch (IOExcetption e){
// catch code
} catch(ResorceAccessException e){
// catch code
}
return employee;
}
CustomRetryPolicy类:
public class CustomRetryPolicy extends ExceptionClassifierRetryPolicy {
private String maxAttempts;
@PostConstruct
public void init() {
final RetryPolicy defaultRetry = defaultRetryPolicy();
this.setExceptionClassifier(new Classifier<Throwable, RetryPolicy>() {
@Override
public RetryPolicy classify(Throwable classifiable) {
Throwable exceptionCause = classifiable.getCause();
if (exceptionCause instanceof HttpStatusCodeException) {
int statusCode = ((HttpStatusCodeException) classifiable.getCause()).getStatusCode().value();
handleHttpErrorCode(statusCode);
}
return neverRetry();
}
});
}
public void setMaxAttempts(String maxAttempts) {
this.maxAttempts = maxAttempts;
}
private RetryPolicy handleHttpErrorCode(int statusCode) {
RetryPolicy retryPolicy = null;
switch(statusCode) {
case 404 :
case 500 :
case 503 :
case 504 :
retryPolicy = defaultRetryPolicy();
break;
default :
retryPolicy = neverRetry();
break;
}
return retryPolicy;
}
private RetryPolicy neverRetry() {
return new NeverRetryPolicy();
}
private RetryPolicy defaultRetryPolicy() {
final SimpleRetryPolicy simpleRetryPolicy = new SimpleRetryPolicy();
simpleRetryPolicy.setMaxAttempts(5);
return simpleRetryPolicy;
}
}