到达api端点时实现“重试”的最佳方法?

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

我正在使用ApacheHttpClient

我有一个Java应用程序,它向外部端点(我不拥有的端点)发出Http POST请求。一切通常都可以正常工作,但有时端点已关闭并发生故障。

Java中是否有用于实现重试模式以击中外部端点的通用设计模式?我知道您可以在Javascript中使用Fetch API并返回一个Promise,是否与Java类似?

java api http endpoint
1个回答
0
投票

[GCP和AWS之类的云平台通常带有其自己的重试策略,这应该是首选方法。

如果您想发挥自己的重试策略作用,指数退缩可能是一个很好的起点。

它可以基于注释,您可以在其中注释客户端方法。例如,您可以如下注释API方法:

@ Retry(maxTries = 3,retryOnExceptions = {RpcException.class}) public UserInfo getUserInfo(String userId);

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Retry {

  int maxTries() default 0;

  /**
   * Attempt retry if one of the following exceptions is thrown.
   * @return array of applicable exceptions
   */
  Class<? extends Throwable> [] retryOnExceptions() default {Throwable.class};
}

方法拦截器可以如下实现:

public class RetryMethodInterceptor implements MethodInterceptor {

  private static final Logger logger = Logger.getLogger(RetryMethodInterceptor.class.getName());

  @Override
  public Object invoke(MethodInvocation methodInvocator) throws Throwable {
    Retry retryAnnotation = methodInvocator.getMethod().getAnnotation(Retry.class);
    Set<Class<? extends Throwable>> retriableExceptions =
        Sets.newHashSet(retryAnnotation.retryOnExceptions());

    String className = methodInvocator.getThis().getClass().getCanonicalName();
    String methodName = methodInvocator.getMethod().getName();

    int tryCount = 0;
    while (true) {
      try {
        return methodInvocator.proceed();
      } catch (Throwable ex) {
        tryCount++;
        boolean isExceptionInAllowedList = isRetriableException(retriableExceptions, ex.getClass());
        if (!isExceptionInAllowedList) {
          System.out.println(String.format(
              "Exception not in retry list for class: %s - method: %s - retry count: %s",
              className, methodName, tryCount));
          throw ex;
        } else if (isExceptionInAllowedList && tryCount > retryAnnotation.maxTries()) {
          System.out.println(String
                  .format(
                      "Exhausted retries, rethrowing exception for class: %s - method: %s - retry count: %s",
                      className, methodName, tryCount));
          throw ex;
        }
        System.out.println(String.format("Retrying for class: %s - method: %s - retry count: %s",
            className, methodName, tryCount));
      }
    }
  }

  private boolean isRetriableException(Set<Class<? extends Throwable>> allowedExceptions,
      Class<? extends Throwable> caughtException) {
    for (Class<? extends Throwable> look : allowedExceptions) {
      // Only compare the class names we do not want to compare superclass so Class#isAssignableFrom
      // can't be used.
      if (caughtException.getCanonicalName().equalsIgnoreCase(look.getCanonicalName())) {
        return true;
      }
    }
    return false;
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.