簡體   English   中英

Spring Boot @Retryable maxAttempts 根據異常

[英]Spring Boot @Retryable maxAttempts according to exception

我想知道有關 Spring Boot @Retryable注釋的一些信息。

我想根據異常類型實現@Retryable maxAttemps 計數,例如:

if Exception type is ExceptionA:
@Retryable(value = ExceptionA.class, maxAttempts = 2)
if Exception type is ExceptionB:
@Retryable(value = ExceptionB.class, maxAttempts = 5)

是否可以使用@Retryable注釋來實現,或者有什么建議嗎?

不直接; 您必須構造一個自定義攔截器 ( RetryInterceptorBuilder ) bean 並在@Retryable.interceptor提供其 bean 名稱。

使用ExceptionClassifierRetryPolicy為每個異常使用不同的策略。

編輯

下面是一個例子:

@SpringBootApplication
@EnableRetry
public class So64029544Application {

    public static void main(String[] args) {
        SpringApplication.run(So64029544Application.class, args);
    }


    @Bean
    public ApplicationRunner runner(Retryer retryer) {
        return args -> {
            retryer.toRetry("state");
            retryer.toRetry("arg");
        };
    }

    @Bean
    public Object retryInterceptor(Retryer retryer) throws Exception {
        ExceptionClassifierRetryPolicy policy = new ExceptionClassifierRetryPolicy();
        policy.setPolicyMap(Map.of(
                IllegalStateException.class, new SimpleRetryPolicy(2),
                IllegalArgumentException.class, new SimpleRetryPolicy(3)));
        Method recover = retryer.getClass().getDeclaredMethod("recover", Exception.class);
        return RetryInterceptorBuilder.stateless()
                .retryPolicy(policy)
                .backOffOptions(1_000, 1.5, 10_000)
                .recoverer(new RecoverAnnotationRecoveryHandler<>(retryer, recover))
                .build();
    }
}

@Component
class Retryer {

    @Retryable(interceptor = "retryInterceptor")
    public void toRetry(String in) {
        System.out.println(in);
        if ("state".equals(in)) {
            throw new IllegalStateException();
        }
        else {
            throw new IllegalArgumentException();
        }
    }

    @Recover
    public void recover(Exception ex) {
        System.out.println("Recovered from " + ex
                + ", retry count:" + RetrySynchronizationManager.getContext().getRetryCount());
    }

}
state
state
Recovered from java.lang.IllegalStateException, retry count:2
arg
arg
arg
Recovered from java.lang.IllegalArgumentException, retry count:3

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM