Я впервые использую Spring Retry. Я пытаюсь повторно ввести код состояния HTTP 5 **. Я взял приведенный ниже вопрос в качестве ссылки и попытался создать собственную политику повторных попыток:
Spring Retry Junit: тестовый шаблон повторных попыток с настраиваемой политикой повторных попыток
но когда я пытаюсь выполнить RetryTemplate, он повторяет попытку только один раз, даже если я установил Максимальное количество попыток больше 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;
}
}