代码之家  ›  专栏  ›  技术社区  ›  user3105453

Hystrix/FIGN仅对HTTP状态429作出反应

  •  0
  • user3105453  · 技术社区  · 7 年前

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

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

    2 回复  |  直到 6 年前
        1
  •  1
  •   Kevin Davis    7 年前

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

    要满足重试要求,请同时注册 Retryer 具有适当配置的bean。请记住,使用 复述者 将在持续时间内绑住一根线。的默认实现 复述者 也使用指数退避策略。

    下面是一个示例ErrorDecoder,摘自 OpenFeign 文件:

    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 用你自己的命令。您需要在所需时间后将此断路器恢复到闭合状态。

        2
  •  0
  •   user3105453    7 年前

    我可以通过以下调整来解决这个问题:

    中的属性 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());
            } 
        }
    }