![](/img/trans.png)
[英]Spring Retry Junit: Testing Retry template with Custom Retry Policy
[英]Executing custom retry policy with retry template
我有一個自定義重試策略,旨在每當應用程序收到不是 404 的 http 狀態代碼時執行重試。我還創建了一個重試模板。 我被困在如何使用重試模板執行自定義重試策略上。 對此以及如何測試我的結果的任何幫助都會非常好。 我已經包含了我的重試模板和自定義重試策略的代碼。
public RetryTemplate retryTemplate() {
RetryTemplate retryTemplate = new RetryTemplate();
FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();
backOffPolicy.setBackOffPeriod(maxBackOffPeriod);
retryTemplate.setBackOffPolicy(backOffPolicy);
NeverRetryPolicy doNotRetry = new NeverRetryPolicy();
SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
retryPolicy.setMaxAttempts(maxAttempts);
retryTemplate.setRetryPolicy(retryPolicy);
return retryTemplate;
}
public class HttpFailedConnectionRetryPolicy extends ExceptionClassifierRetryPolicy {
@Value("${maxAttempts:-1}")
private String maxAttempts;
public void HttpFailedConnectionRetryPolicy() {
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();
return handleHttpErrorCode(statusCode);
}
return simpleRetryPolicy();
}
});
}
public void setMaxAttempts(String maxAttempts) {
this.maxAttempts = maxAttempts;
}
private RetryPolicy handleHttpErrorCode(int statusCode) {
RetryPolicy retryPolicy = null;
switch (statusCode) {
case 404:
retryPolicy = doNotRetry();
break;
default:
retryPolicy = simpleRetryPolicy();
break;
}
return retryPolicy;
}
private RetryPolicy doNotRetry() {
return new NeverRetryPolicy();
}
private RetryPolicy simpleRetryPolicy() {
final SimpleRetryPolicy simpleRetryPolicy = new SimpleRetryPolicy();
simpleRetryPolicy.setMaxAttempts(Integer.valueOf(maxAttempts));
return simpleRetryPolicy;
}
}
只需將重試策略的實例注入模板而不是SimpleRetryPolicy
。
要進行測試,您可以將RetryListener
添加到測試用例中的模板中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.