gpt4 book ai didi

java - 访问 api 端点时实现 "retries"的最佳方法?

转载 作者:行者123 更新时间:2023-12-01 16:15:31 26 4
gpt4 key购买 nike

我正在使用ApacheHttpClient

我有一个 Java 方法(在 Java 微服务内),它向外部端点(我不拥有的端点)发出 Http POST 请求。通常一切都运行良好,但有时端点会出现故障。代码看起来像这样(简化):

private HttpResponseData postRequest(String url) throws Exception {
HttpResponseData response = null;
try (InputStream key = MyAPICaller.class.getResourceAsStream(keyPath)) {
MyAPICaller.initializeApiClient(Username, PassString, key);
int attempts = REQUEST_RETRY_COUNT; // starts at 3

while (attempts-- > 0) {
try {
response = MyAPICaller.getInstance().post(url);
break;
} catch (Exception e) {
log.error("Post Request to {} failed. Retries remaining {}", url, attempts);
Thread.sleep(REQUEST_RETRY_DELAY * 1000);
}
}

if (response == null)
throw new Exception("Post request retries exceeded. Unable to complete request.");

}
return response;
}

我没有编写原始代码,但正如您所看到的,它看起来像是发出了一个请求,并且虽然 REQUEST_RETRY_COUNT 大于 0(看起来总是如此) ,它会尝试向该网址发布帖子。看起来由于某种原因那里有一个断点,所以它跳转到 try block 后,总是会跳出,并且没有重试机制。

Java 中是否有通用的设计模式来实现命中外部端点的重试模式?我知道在 Javascript 中你可以使用 Fetch API 并返回一个 promise ,Java 有类似的东西吗?

最佳答案

像 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;
}
}

关于java - 访问 api 端点时实现 "retries"的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62400839/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com