【转】spring-restry实现接口超时重试

一、在pom.xml中添加依赖

    <dependency>
        <groupId>org.springframework.retry</groupId>
        <artifactId>spring-retry</artifactId>
    </dependency>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.9.1</version>
    </dependency>

二、在Application.class启动类中添加注解

package com.jia.bill;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.retry.annotation.EnableRetry;

@EnableRetry
@SpringBootApplication
public class BillApplication {

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

}

三、在serviceImpl的方法上添加注解@Retryable

package com.jia.bill.service.serviceImpl;

import com.jia.bill.service.TestRetryService;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import java.time.LocalTime;

@Service
public class TestRetryServiceImpl implements TestRetryService {

    @Override
    @Retryable(value = Exception.class,maxAttempts = 3,backoff = @Backoff(delay = 2000,multiplier = 1.5))
    public int retryServiceTest(int code) throws Exception{
        System.out.println("retryServiceTest被调用,时间:"+ LocalTime.now());
        if (code==0){
            throw new Exception("请求参数为0,出现异常");
//            throw new IllegalArgumentException("非法数据");
        }
        System.out.println("retryServiceTest被调用,情况对头了!");
        return 200;
    }

    @Recover
    public int recover(Exception e){ //返回的类型要和上面保持一致,且@Retryable只能写在直接调用的方法上,写在内部调用的方法上不生效
        System.out.println("重试次数结束后还有异常,回调方法开始执行");
        //可调用其余的方法
        return 400;
    }

}

当调用TestRetryServiceImpl 中的retryServiceTest时,如果抛出了异常Exception,就会被重试,重试3次。

但是如果三次都失败了,并且写了recover方法时,就会执行recover方法了。如果没有此方法会直接抛出异常。

其中注解解释:

  • @Retryable : 注解方式标记当前方法会使用重试机制
  • value: 重试的触发机制,当遇到Exception异常的时候,触发;
  • maxAttempts: 重试的次数(包括第一次调用,也就是说如果设置3次,调用一次后,如果一直失败触发重试,那么还当前方法还会调用2次);
  • delay:重试的延迟时间,也就是距离上一次重试方法调用的间隔,单位毫秒
  • multiplier: delay间隔时间的倍数,也就是说,第一次重试间隔如果是2000ms,那第二次重试的时候就是2000ms 乘以这个倍数1.5,就是3000ms;
  • maxDelay:重试次数之间的最大时间间隔,默认为0,即忽略,如果小于delay的设置,则默认为30000L;
  • @Recover,也就是用注解方式标记当期方法为回调方法,可以看到传参里面写的是 Exception e,这个是作为回调的接头暗号(重试次数用完了,还是失败,我们抛出这个Exception e通知触发这个回调方法)。

posted on 2020-11-18 20:06  程序员大禹  阅读(338)  评论(0编辑  收藏  举报

导航