我们可以使用spring retry处理嵌套异常吗?

问题描述 投票:0回答:1

我正在学习Spring Retry,并对其功能有以下疑问:

我有一个连接到第三方应用程序API的函数。预计这会引发不同的异常,例如超时或IO异常。我试图查看spring的重试模板是否能够处理“每个”事件中的此类嵌套异常。例如,当我们将个别异常的maxAttempts设置为3时,则即使每次重试也要尝试3次。例如,在尝试1-发生异常1之后,下一次尝试(尝试2)成功了,但是现在发生了异常2,基于retryPolicy,它应该为异常2启动尝试1。

这可能吗?

基于一个小的POC,即使同时抛出两种类型,我也看到它仅尝试3次:

带有retryTemplate的控制器类:

         retryTemplate.execute(new RetryCallback<Customer, Exception>(){
             @Override
                public Customer doWithRetry(RetryContext arg0) throws Exception{
                System.out.println("count #"+arg0.getRetryCount());
                if(arg0.getRetryCount()>0) {
                    System.out.println("throwable getClass Canonical Name "+arg0.getLastThrowable().getClass().getCanonicalName());
                }

                return  customerService.getCustomerDetails(choice);
             }});

异常模拟类:

Random r = new Random();

            int i = r.nextInt();
            i+=1;

            System.out.println("value of i "+i);
            if(i%2==0) {
                throw new Exception1();
            }
            else {
                throw new Exception2();
            }

以下是日志:

count #0
in getCustomerDetails
value of i -1050226395
count #1
throwable getClass Canonical Name Exception1
in getCustomerDetails
value of i 824190506
count #2
throwable getClass Canonical Name Exception2
in getCustomerDetails
value of i 1210506150
Exception1

预期结果:每次发生异常都尝试3次

实际结果:仅尝试总计3个。

下面是我的RetryPolicy:ExceptionClassifierRetryPolicy具有两种类型的异常的policyMap

public RetryTemplate retryTemplate() {

    RetryTemplate retryTemplate = new RetryTemplate();
    final SimpleRetryPolicy simpleRetryPolicy = new SimpleRetryPolicy();
    simpleRetryPolicy.setMaxAttempts(3);
    FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();
    backOffPolicy.setBackOffPeriod(1500);
    final Map<Class<? extends Throwable>, RetryPolicy> policyMap = new HashMap<>();
    policyMap.put(Exception1.class, simpleRetryPolicy);
    policyMap.put(Exception2.class, simpleRetryPolicy);
    final ExceptionClassifierRetryPolicy retryPolicy = new ExceptionClassifierRetryPolicy();
    retryPolicy.setPolicyMap(policyMap);
    retryTemplate.setBackOffPolicy(backOffPolicy);
    retryTemplate.setRetryPolicy(retryPolicy);
    return retryTemplate;
}

问题:

  1. 在这种情况下可以使用Spring重试吗?
  2. 如果是,那么在上述实现中需要更改什么?
  3. 请指导。

我正在学习Spring Retry,并对其功能有以下疑问:我有一个连接到第三方应用程序API的函数。预计这会引发不同的...

spring-boot spring-retry
1个回答
0
投票

您可以使用ExceptionClassifierRetryPolicy:

© www.soinside.com 2019 - 2024. All rights reserved.