java - 使用重试模板执行自定义重试策略

标签 java maven spring-boot spring-retry

我有一个自定义重试策略,旨在每当应用程序收到非 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)注入(inject)到模板中。

要进行测试,您可以将 RetryListener 添加到测试用例中的模板。

关于java - 使用重试模板执行自定义重试策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58332214/

相关文章:

java - Java ArrayDeque 中的 pop() 和 remove() 之间有本质区别吗?

java - 在 Spring Boot 应用程序中动态计划任务

xml - <plugins> pom xml 中无法识别的标记

java - 目标服务器未能响应

java 。 Spring Boot 。应用程序启动失败

java - Reactor Core - Mono - onError Flatmap

Java - Maven - 在客户端和服务器端项目中重用实体层

java - 在 Android/Java 中使用 JSON/Base64 编码的文件

java - 如何解析 "dd-MM"日期格式以获取当前年份?”

java - 带有嵌入式 tomcat 的 Spring Boot 应用程序