首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Resilience4j重试和"java.net.http.HttpClient“协同工作的麻烦

Resilience4j重试和"java.net.http.HttpClient“协同工作的麻烦
EN

Stack Overflow用户
提问于 2020-09-18 08:23:51
回答 1查看 1.5K关注 0票数 0

我正在尝试让一个基本的"httpclient“"httprequest”"httpresponse“使用Resilience4j重试。

来自:https://resilience4j.readme.io/docs/retry的逐字代码

代码语言:javascript
复制
  RetryConfig config = RetryConfig.custom()
  .maxAttempts(5)
  .waitDuration(Duration.ofMillis(1000))
  .retryOnResult(response -> response.getStatus() == 500)
  .retryOnException(e -> e instanceof WebServiceException)
  .retryExceptions(IOException.class, TimeoutException.class)
  .ignoreExceptions(BusinessException.class, OtherBusinessException.class)
  .build();

// Create a RetryRegistry with a custom global configuration
RetryRegistry registry = RetryRegistry.of(config);

// Get or create a Retry from the registry - 
// Retry will be backed by the default config
Retry retryWithDefaultConfig = registry.retry("name1");

注意,上面的代码没有定义泛型"T",如下所示:

代码语言:javascript
复制
  RetryConfig config = RetryConfig.<MyConcrete>custom()

以及来自:https://resilience4j.readme.io/docs/examples的逐字代码

代码语言:javascript
复制
Supplier<String> supplierWithResultAndExceptionHandler = SupplierUtils
  .andThen(supplier, (result, exception) -> "Hello Recovery");

Supplier<HttpResponse> supplier = () -> httpClient.doRemoteCall();
Supplier<HttpResponse> supplierWithResultHandling = SupplierUtils.andThen(supplier, result -> {
    if (result.getStatusCode() == 400) {
       throw new ClientException();
    } else if (result.getStatusCode() == 500) {
       throw new ServerException();
    }
    return result;
});
HttpResponse httpResponse = circuitBreaker
  .executeSupplier(supplierWithResultHandling);

======

所以使用这两个“部分”,我想出了这个。

注意,我使用的是一些“真实的”java.net.http.HttpClient和java.net.http.HttpResponse (来自JDK11)

代码语言:javascript
复制
import io.github.resilience4j.core.SupplierUtils;
import io.github.resilience4j.retry.Retry;
import io.github.resilience4j.retry.RetryConfig;
import io.github.resilience4j.retry.RetryRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;

import javax.inject.Inject;
import java.io.IOException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.concurrent.TimeoutException;
import java.util.function.Supplier;

public final class ResilientHttpClient /* implements IResilientHttpClient */ {

    private static Logger logger;

    private final HttpClient httpClient;

    @Inject
    public ResilientHttpClient(final HttpClient httpClient) {
        this(LoggerFactory
                .getLogger(ResilientHttpClient.class), httpClient);
    }

    /**
     * Constructor, which pre-populates the provider with one resource instance.
     */
    public ResilientHttpClient(final Logger lgr,
                               final HttpClient httpClient) {
        if (null == lgr) {
            throw new IllegalArgumentException("Logger is null");
        }
        this.logger = lgr;

        if (null == httpClient) {
            throw new IllegalArgumentException("HttpClient is null");
        }

        this.httpClient = httpClient;

    }

    public String executeHttpRequest(String circuitbreakerInstanceName, HttpRequest httpRequest) {

        try {

            /* circuitbreakerInstanceName  is future place holder for .yml configuration see : https://resilience4j.readme.io/docs/getting-started-3 */

        RetryConfig config = RetryConfig.<HttpResponse>custom()
                    .waitDuration(Duration.ofMillis(1000))
                    .retryOnResult(response -> response.statusCode() == 500)
                    .retryOnException(e -> e instanceof ArithmeticException)
                    .retryExceptions(IOException.class, TimeoutException.class)
                    //.ignoreExceptions(BusinessException.class, OtherBusinessException.class)
                    .build();

            // Create a RetryRegistry with a custom global configuration
            RetryRegistry registry = RetryRegistry.of(config);

            // Get or create a Retry from the registry -
            // Retry will be backed by the default config
            Retry retryWithDefaultConfig = registry.retry(circuitbreakerInstanceName);

            Supplier<HttpResponse> supplier = () -> this.httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());

            Supplier<String> supplierWithResultAndExceptionHandler = SupplierUtils
                    .andThen(supplier, (result, exception) -> "Hello Recovery");

            Supplier<HttpResponse> supplierWithResultHandling = SupplierUtils.andThen(supplier, result -> {
                if (result.statusCode() == HttpStatus.BAD_REQUEST.value()) {
                    throw new RuntimeException("400");
                } else if (result.statusCode() == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
                    throw new RuntimeException("500");
                }
                return result;
            });

            HttpResponse<String> response = retryWithDefaultConfig.executeSupplier(supplierWithResultHandling);

            String responseBody = response.body();

            return responseBody;

        } catch (Exception ex) {
            throw new RuntimeException((ex));
        }
    }

}

我面临的问题是:

这句话:

代码语言:javascript
复制
Supplier<HttpResponse> supplier = () - > this.httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());

在intelliJ中给出“未处理异常”"IOException,InterruptedException“的错误。

因此,将方法修改为:

代码语言:javascript
复制
 public String executeHttpRequest(String circuitbreakerInstanceName, HttpRequest httpRequest) throws IOException, InterruptedException {

“感觉不对”。但是,即使我尝试,it...it也解决不了任何问题。:(

可能是一些兰达检查过的例外巫毒。

但更重要的是:

所以我不知道我把两个部分组合在一起的方式是否正确。在全工作区,样品有一点不足.

谢谢你的帮助。获得一个基本的httpclient“重试”几次应该不会太难。但我的头撞在墙上了。

我的等级依赖关系。

代码语言:javascript
复制
dependencies {

    implementation group: 'javax.inject', name: 'javax.inject', version: javaxInjectVersion
    implementation group: 'org.slf4j', name: 'slf4j-api', version: slf4jVersion

    implementation group: 'org.springframework', name: 'spring-web', version: springWebVersion

    implementation "io.github.resilience4j:resilience4j-circuitbreaker:${resilience4jVersion}"
    implementation "io.github.resilience4j:resilience4j-ratelimiter:${resilience4jVersion}"
    implementation "io.github.resilience4j:resilience4j-retry:${resilience4jVersion}"
    implementation "io.github.resilience4j:resilience4j-bulkhead:${resilience4jVersion}"
    implementation "io.github.resilience4j:resilience4j-cache:${resilience4jVersion}"
    implementation "io.github.resilience4j:resilience4j-timelimiter:${resilience4jVersion}"


    testCompile group: 'junit', name: 'junit', version: junitVersion
}

代码语言:javascript
复制
   resilience4jVersion = '1.5.0'
    slf4jVersion = "1.7.30"
    javaxInjectVersion = "1"
 springWebVersion = '5.2.8.RELEASE'
    junitVersion = "4.12"
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-09-22 10:28:13

只是出于兴趣:

  • 您使用的是哪个Java版本?Java11?
  • 为什么不能使用Spring?Resilience4j Spring启动器大大简化了配置。

如果配置retryOnResult(response -> response.getStatus() == 500),则不必再使用SupplierUtils将具有特定状态代码的HttpResponse映射到运行时异常。

代码语言:javascript
复制
RetryConfig config = RetryConfig.<HttpResponse<String>>custom()
            .waitDuration(Duration.ofMillis(1000))
            .retryOnResult(response -> response.statusCode() == 500)
            .retryExceptions(IOException.class, TimeoutException.class)
            .build();

请不要在executeHttpRequest中创建注册表和Con图,而是将它们注入到构造器中。

您可以创建这样的静态方法:

代码语言:javascript
复制
public static <T> HttpResponse<T> executeHttpRequest(Callable<HttpResponse<T>> callable, Retry retry, CircuitBreaker circuitBreaker) throws Exception {
        return Decorators.ofCallable(callable)
            .withRetry(retry)
            .withCircuitBreaker(circuitBreaker)
            .call();
}

并按以下方式调用该方法:

代码语言:javascript
复制
HttpResponse<String> response = executeHttpRequest(
    () -> httpClient.send(request, HttpResponse.BodyHandlers.ofString()), 
    retry, 
    circuitBreaker);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63951963

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档