我正在使用 RestAssured 来触发 API 调用,并希望在 REST 调用失败时实现重试逻辑。
此要求是因为我们会收到某些 API 的间歇性 500 响应代码,这些代码通常需要重试才能正常工作。
我已经实现了以下代码,但它似乎不起作用 -
HttpClientConfig.HttpClientFactory htc = new HttpClientConfig.HttpClientFactory() {
@Override
public HttpClient createHttpClient() {
DefaultHttpClient d = new DefaultHttpClient();
d.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(restRetryCount, true));
return d;
}
};
RestAssuredConfig rac = RestAssured.config().httpClient(HttpClientConfig.httpClientConfig().httpClientFactory(htc));
此外,由于 RestAssured 不满足 HTTPClient 级别的日志记录,我尝试使用 java.util.logging 为 apache httpclient 启用日志记录,但这也似乎也不起作用。
创建了一个 custom.logging.properties 文件 -
# Enables the header wire and context logging
org.apache.http.level = FINEST
org.apache.http.wire.level = SEVERE
# Enables the context logging for connection management & request execution
org.apache.http.impl.conn.level = FINEST
org.apache.http.impl.client.level = FINEST
org.apache.http.client.level = FINEST
并编写了以下内容以启动日志记录 -
public static Logger initiateHttpTrafficLogging(){
Logger log = Logger.getLogger("httptraffic.log");
ClassLoader loader = Thread.currentThread().getContextClassLoader();
InputStream is = loader.getResourceAsStream("custom.logging.properties");
try{
LogManager.getLogManager().readConfiguration(is);
log.setLevel(Level.FINEST);
log.addHandler(new ConsoleHandler());
log.setUseParentHandlers(false);
log.info("Initiating HTTP Traffic logging ::\n\n");
} catch (IOException ie){
Assert.fail("ERROR: Could not load the loggin properties !!!", ie.fillInStackTrace());
}
return log;
}
任何人都可以就我哪里出错或解决此问题的任何指示向我提供一些指导。
感谢您的回复。 谢谢。
最佳答案
有一个 Spring-retry jar,你可以将它与你的应用程序集成。你可以在你的方法中使用类似的东西
@Retryable(maxAttempts = 4, backoff = @Backoff(delay = 200),
include = {RetryableException.class})
ResponseEntity<String> request(
String url, HttpMethod method, HttpEntity<?> entity, Class<?> type,
Map<String, String> parameters
) throws Exception{}
and u need to do @EnableAspectJAutoProxy and @EnableRetry in your configuration class
关于java - 如何在 Rest Assured 中为失败的 REST 调用实现重试逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42548226/