【问题标题】:Hystrix/Feign to solely react on HTTP status 429Hystrix/Feign 仅对 HTTP 状态 429 做出反应
【发布时间】:2018-08-12 05:05:56
【问题描述】:

我正在使用spring-cloud-starter-feign 中的Feign 将请求发送到定义的后端。我想使用Hystrix 作为断路器,但仅用于一种类型的用例:如果后端以HTTP 429: Too many requests 代码响应,我的 Feign 客户端应该等待整整一小时,直到它再次联系真正的后端。在那之前,应该执行一个回退方法。

我必须如何配置我的 Spring Boot (1.5.10) 应用程序才能做到这一点?我看到了许多配置可能性,但只有少数示例 - 在我看来 - 不幸的是没有围绕用例解决。

【问题讨论】:

    标签: spring-cloud-netflix hystrix spring-cloud-feign http-status-code-429


    【解决方案1】:

    我可以通过以下调整来解决它:

    application.yml 中的属性:

    hystrix.command.commandKey:
      execution.isolation.thread.timeoutInMilliseconds: 10_000
      metrics.rollingStats.timeInMilliseconds: 10_000
      circuitBreaker:
        errorThresholdPercentage: 1
        requestVolumeThreshold: 1
        sleepWindowInMilliseconds: 3_600_000
    

    相应 Java 类中的代码:

    @HystrixCommand(fallbackMethod = "fallbackMethod", commandKey = COMMAND_KEY)
    public void doCall(String parameter) {
        try {
            feignClient.doCall(parameter);
        } catch (FeignException e) {
            if (e.status() == 429) {
                throw new TooManyRequestsException(e.getMessage());
            } 
        }
    }
    

    【讨论】:

      【解决方案2】:

      这可以通过定义ErrorDecoder 并手动控制Hystrix 断路器来实现。您可以检查异常的响应代码并提供您自己的回退。此外,如果您希望重试请求,请将您的异常包装并抛出RetryException

      为了满足您的重试要求,还要注册一个具有适当配置的Retryer bean。请记住,使用Retryer 将在持续时间内占用一个线程。 Retryer 的默认实现也确实使用了指数退避策略。

      这是一个来自OpenFeign 文档的示例 ErrorDecoder:

      public class StashErrorDecoder implements ErrorDecoder {
      
          @Override
          public Exception decode(String methodKey, Response response) {
              if (response.status() >= 400 && response.status() <= 499) {
                  return new StashClientException(
                      response.status(),
                      response.reason()
                  );
              }
              if (response.status() >= 500 && response.status() <= 599) {
                  return new StashServerException(
                      response.status(),
                      response.reason()
                  );
              }
              return errorStatus(methodKey, response);
          } 
      }
      

      在您的情况下,您可以根据需要对419 做出反应。

      您可以在运行时强制打开断路器设置此属性

      hystrix.command.HystrixCommandKey.circuitBreaker.forceOpen

      ConfigurationManager.getConfigInstance()
          .setProperty(
          "hystrix.command.HystrixCommandKey.circuitBreaker.forceOpen", true);
      

      用您自己的命令替换HystrixCommandKey。您需要在所需时间后将此断路器恢复为闭合状态。

      【讨论】:

      猜你喜欢
      • 2020-05-18
      • 2020-07-26
      • 1970-01-01
      • 2021-08-31
      • 2021-06-06
      • 1970-01-01
      • 2016-09-15
      • 2019-08-18
      • 2021-08-19
      相关资源
      最近更新 更多