【发布时间】:2019-10-24 14:38:03
【问题描述】:
我正在使用 resilience4j 重试策略来调用 HttpGet 请求并用于测试目的,
我已将retryOnResult 设置为在HttpGet 请求返回200 状态码时重试。
当maxAttempts 设置为2 时,它会成功重试。
对于maxAttempts > 2,应用程序进入无限状态。
public class App {
public static void main(String[] args) {
HttpClient client = HttpClients.createDefault();
HttpRequest request = new HttpGet("https://jsonplaceholder.typicode.com/todos/1");
HttpResponse response;
try {
RetryConfig retryConfig = RetryConfig.<HttpResponse>custom().waitDuration(Duration.ofSeconds(2))
.maxAttempts(3).retryOnResult(s -> {
return s.getStatusLine().getStatusCode() == 200;
}).build();
RetryRegistry registry = RetryRegistry.of(retryConfig);
Retry retry = registry.retry("Http client");
retry.getEventPublisher().onRetry(e -> {
System.out.println("Retrying");
});
CheckedFunction0<HttpResponse> retryableSupplier = Retry.decorateCheckedSupplier(retry,
() -> client.execute((HttpUriRequest) request));
response = Try.of(retryableSupplier).get();
HttpEntity entity = response.getEntity();
System.out.println(EntityUtils.toString(entity));
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
pom.xml:
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
<dependency>
<groupId>io.github.resilience4j</groupId>
<artifactId>resilience4j-circuitbreaker</artifactId>
<version>1.1.0</version>
</dependency>
<dependency>
<groupId>io.github.resilience4j</groupId>
<artifactId>resilience4j-retry</artifactId>
<version>1.1.0</version>
</dependency>
</dependencies>
【问题讨论】:
标签: java httpresponse retrypolicy resilience4j