API请求重试的8种方法,你用哪种?( 三 )

RetryRegistry retryRegistry = RetryRegistry.ofDefaults();

  1. 配置Retry实例:接下来 , 可以通过RetryRegistry对象创建和配置Retry实例 。可以使用RetryConfig类来自定义Retry的配置,包括最大重试次数、重试间隔等 。
RetryConfig config = RetryConfig.custom().maxAttempts(3).waitDuration(Duration.ofMillis(1000)).retryOnResult(response -> response.getStatus() == 500).retryOnException(e -> e instanceof WebServiceException).retryExceptions(IOException.class, TimeoutException.class).ignoreExceptions(BusinessException.class, OtherBusinessException.class).failAfterMaxAttempts(true).build();Retry retry = retryRegistry.retry("name", config);通过以上代码,我们创建了一个名为"name"的Retry实例,并配置了最大重试次数为3次,重试间隔为1秒,当返回结果的状态码为500时进行重试,当抛出WebServiceException异常时进行重试,忽略BusinessException和OtherBusinessException异常,达到最大重试次数后抛出
MaxRetriesExceededException异常 。
  1. 使用Retry调用:最后,可以使用Retry来装饰和执行需要进行重试的代码块 。比如,可以使用Retry.decorateCheckedSupplier()方法来装饰一个需要重试的Supplier 。
CheckedFunction0<String> retryableSupplier = Retry.decorateCheckedSupplier(retry, () -> {// 需要进行重试的代码return "result";});通过注解调用通过注解的方式,使用Resilience4j来使用重试功能,更加简洁 。
在Spring Boot项目中,可以使用@Retryable注解来标记需要进行重试的方法 。
@Servicepublic class MyService {@Retryable(value = https://www.isolves.com/it/cxkf/bk/2023-11-10/{MyException.class}, maxAttempts = 3, backoff = @Backoff(delay = 1000))public void doSomething() {// 需要进行重试的方法逻辑}}代码里,@Retryable注解标记了doSomething()方法,指定了重试的异常类型为MyException.class,最大重试次数为3次,重试间隔为1秒 。
6.自定义重试工具类如果说我们不想在项目里额外地引入一些重试的框架,自己定义一个重试工具类也是可以的 , 这是我在某个第三方提供的client-sdk里发现的一套重试工具类,比较轻量级,给大家分享一下 。
  • 首先,定义一个实现了Callback抽象类的具体回调类,实现其中的doProcess()方法来执行需要重试的逻辑 。回调类的doProcess()方法返回一个RetryResult对象,表示重试的结果 。
public abstract class Callback {public abstract RetryResult doProcess();}
  • 然后,定义一个RetryResult类 , 用于封装重试的结果 。RetryResult类包含一个isRetry属性表示是否需要进行重试,以及一个obj属性表示重试的结果对象 。
public class RetryResult {private Boolean isRetry;private Object obj;// 构造方法和getter方法省略public static RetryResult ofResult(Boolean isRetry, Object obj){return new RetryResult(isRetry, obj);}public static RetryResult ofResult(Boolean isRetry){return new RetryResult(isRetry, null);}}
  • 最后,定义一个RetryExecutor类,其中的execute()方法接收一个重试次数和一个回调对象,根据重试次数循环执行回调对象的doProcess()方法,直到达到最大重试次数或回调对象返回不需要重试的结果 。
public class RetryExecutor {public static Object execute(int retryCount, Callback callback) {for (int curRetryCount = 0; curRetryCount < retryCount; curRetryCount++) {RetryResult retryResult = callback.doProcess();if (retryResult.isRetry()) {continue;}return retryResult.getObj();}return null;}}
  • 使用这个自定义的重试工具类时,只需要实现一个继承自Callback的回调类,并在其中实现具体的重试逻辑 。然后,通过调用RetryExecutor.execute()方法来执行重试操作 。这里直接用了一个匿名的实现:
//最大重试次数int maxRetryCount = 3;Object result = RetryExecutor.execute(maxRetryCount, new Callback() {@Overridepublic RetryResult doProcess() {// 执行需要重试的逻辑// 如果需要重试,返回 RetryResult.ofResult(true)// 如果不需要重试,返回 RetryResult.ofResult(false, result)}});7.并发框架异步重试在有些需要快速响应的场景下,我们可以使用并发框架,来实现异步的重试 。
比如使用线程池ThreadPoolExecutor,把请求接口转化成一个异步任务 , 将任务放入线程池中异步执行,并发地重试请求接口 。可以在任务执行完成后,判断任务执行结果,如果失败则继续重试 。
int maxRetryTimes = 3;int currentRetryTimes = 0;ThreadPoolExecutor executor = new ThreadPoolExecutor(10,// 核心线程数10,// 最大线程数0L,// 空闲线程存活时间TimeUnit.MILLISECONDS,// 时间单位new LinkedBlockingQueue<>()// 任务队列);Callable<String> task = () -> {// 请求接口的代码return "result";};Future<String> future;while (currentRetryTimes < maxRetryTimes) {try {future = executor.submit(task);String result = future.get();// 判断任务执行结果break;} catch (Exception e) {currentRetryTimes++;// 处理异常try {Thread.sleep(1000);} catch (InterruptedException ex) {Thread.currentThread().interrupt();}}}


推荐阅读